Reputation: 511866
I have a ListView that is being populated (at different times) by two different custom ArrayAdapters (AdapterA
and AdapterB
). When a user clicks a ListView row I want to know which adapter is currently being used so that I can take the appropriate action and extract the data I need from that adapter.
I'd like to do something like the following:
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
if (isAdapterA) {
// do something with AdapterA
} else if (isAdapterB) {
// do something with AdapterB
}
}
But I don't know how to get a reference to and determine which adapter is currently populating the ListView.
Upvotes: 0
Views: 290
Reputation: 3063
If your ListView has a header, your
parent.getAdapter()
will return an HeaderViewListAdapter and wont match AdapterA or AdapterB.
If you use Listview with header consider this:
ListAdapter adapter = ((HeaderViewListAdapter) ((ListView) parent).getAdapter()).getWrappedAdapter();
if(adapter instanceof AdapterA){
//Do something with Adapter A
}else if(adapter instanceof AdapterB){
//Do something with Adapter B
}
If you don't use any Header, check the answer from Suragch.
Upvotes: 2
Reputation: 511866
You can use
(parent.getAdapter() instanceof CustomAdapterClass)
So the onItemClick method would be
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
if (parent.getAdapter() instanceof AdapterA) {
// do something with AdapterA
// If AdapterA were an ArrayAdapter of custom objects then
// data from those objects could be retrieved like this:
AdapterA adapter = (AdapterA) parent.getAdapter();
String myString = adapter.getItem(position).getMyObjectData();
} else if (parent.getAdapter() instanceof AdapterB) {
// do something with AdapterB
// If AdapterB were an ArrayAdapter of Strings then
// they could be retrieved like this:
String text = parent.getAdapter().getItem(position).toString();
}
}
Upvotes: 1