onItemClick(AdapterView parent, View v, int position, long id) 事件的行为不像我想要的那样。
这是过滤适配器时的正常情况。尽管适配器从它的角度保持对初始未过滤数据的引用,但它有一组数据作为其基础(无论是初始数据还是过滤操作的结果)。但这不应该引起任何问题。使用默认的 sdk 适配器(或使用子类),onItemClick()
您将获得适配器所基于position
的当前列表。然后,您可以使用它getItem()
来获取数据项position
(同样,无论是初始还是过滤都无关紧要)。
String data = getItem(position);
int realPosition = list.indexOf(data); // if you want to know the unfiltered position
这将适用于列表和Maps
(假设您使用SimpleAdapter
)。对于一个Maps
您总是可以选择添加一个额外的键来设置初始列表中的未过滤位置。
如果您将自己的适配器与 an 一起使用,则AutoCompleteTextView
可以使onItemClick()
您获得正确的权利id
(但是您无法更改的位置)。
public class SpecialAutoComplete extends AutoCompleteTextView {
public SpecialAutoComplete(Context context) {
super(context);
}
@Override
public void onFilterComplete(int count) {
// this will be called when the adapter finished the filter
// operation and it notifies the AutoCompleteTextView
long[] realIds = new long[count]; // this will hold the real ids from our maps
for (int i = 0; i < count; i++) {
final HashMap<String, String> item = (HashMap<String, String>) getAdapter()
.getItem(i);
realIds[i] = Long.valueOf(item.get("id")); // get the ids from the filtered items
}
// update the adapter with the real ids so it has the proper data
((SimpleAdapterExtension) getAdapter()).setRealIds(realIds);
super.onFilterComplete(count);
}
}
和适配器:
public class SimpleAdapterExtension extends SimpleAdapter {
private List<? extends Map<String, String>> mData;
private long[] mCurrentIds;
public SimpleAdapterExtension(Context context,
List<? extends Map<String, String>> data, int resource,
String[] from, int[] to) {
super(context, data, resource, from, to);
mData = data;
}
@Override
public long getItemId(int position) {
// this will be used to get the id provided to the onItemClick callback
return mCurrentIds[position];
}
@Override
public boolean hasStableIds() {
return true;
}
public void setRealIds(long[] realIds) {
mCurrentIds = realIds;
}
}
如果您还实现了Filter
适配器的类,那么您可以从那里获取 id 而无需覆盖AutoCompleTextView
该类。