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

How to know which of two adapters is being used in ListView onItemClick?

我有一个 ListView(在不同时间)由两个不同的自定义 ArrayAdapter(AdapterAAdapterB)填充。当用户单击 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。

您可以使用

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

如果您的 ListView 有 header,您的

parent.getAdapter()

将 return 一个 HeaderViewListAdapter 并且不会匹配 AdapterA 或 AdapterB。

如果您将 Listview 与 header 一起使用,请考虑:

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            
}

如果您不使用任何 Header,请查看 Suragch 的答案。