Accessing new custom BaseAdapter function in Android

113 Views Asked by At

In my main activity I have a calendarListView which of type HorizontalListView (custom).

The adapter for this is set as such:

calendarListView.setAdapter(new CustomCalendarAdapter(this, listArrayX, listArrayY));

This works fine and I can access all functions within the CustomCalendarAdapter since by default they are just overriding the base adapter.

Since the adapter is passed into the listview class, the HorizontalListView itself does not know anything about the CustomCalendarAdapter, i.e. as long as the functions exist in the base adapter class, it builds fine.

Now, in the custom calendar adapter I have added a new function.

So, for example:

public class CustomCalendarAdapter extends BaseAdapter{

...

public int getItemDate()
{
    return 5;
}

How can I access that function from within the HorizontalListView?

I am trying to use mAdapter.getItemDate.

(mAdapter is set in the setAdapter function)

    @Override
    public void setAdapter(ListAdapter adapter) {
        if (mAdapter != null) {
            mAdapter.unregisterDataSetObserver(mDataObserver);
        }
        mAdapter = adapter;
        mAdapter.registerDataSetObserver(mDataObserver);
        mDataChanged = true;
        requestLayout();
//      reset();
    }

As I mentioned, the adapter is passed in within setAdapter so at build time functions within the CustomCalendarAdapter are not understood.

The only approach I can think of is to hardwire the CustomCalendarAdapter to the HorizontalListView which I'd prefer to not do!

Doing so, i.e. changing all instances of ListAdapter to CustomCalendarAdapter works correctly, however this isn't a sensible way of working I believe.

Any help is appreciated.

1

There are 1 best solutions below

2
Nick H On BEST ANSWER

What I would do is put the custom functionality into an interface

public interface CustomAdapterFunctions {
    int getItemDate();
}

Then inside the setAdapter method, cast ListAdapter to CustomAdapterFunctions

try {
    CustomAdapterFunctions custom = (CustomAdapterFunctions) listAdapter;
catch (ClassCastException ex){
    throw new ClassCastException("Adapters must implement CustomAdapterFunctions!");
}

Make sure any adapter you use implements this interface before using it with the CalendarListView.