如何知道ListView onItemClick中使用了哪两个适配器?

时间:2015-05-07 16:01:41

标签: android android-listview android-arrayadapter

我有一个由两个不同的自定义ArrayAdapter(AdapterAAdapterB)填充的ListView(在不同时间)。当用户单击ListView行时,我想知道当前正在使用哪个适配器,以便我可以采取适当的操作并从该适配器中提取我需要的数据。

我想做以下事情:

@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
    }
}

但我不知道如何获取引用并确定哪个适配器当前正在填充ListView。

2 个答案:

答案 0 :(得分:2)

如果您的ListView有标题,那么

  

parent.getAdapter()

将返回HeaderViewListAdapter并且不匹配AdapterA或AdapterB。

如果您使用带有标题的Listview,请考虑以下事项:

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            
}

如果您不使用任何标题,请检查Suragch的答案。

答案 1 :(得分:1)

您可以使用

(parent.getAdapter() instanceof CustomAdapterClass)

所以onItemClick方法将是

@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();
    }
}