事件onItemClick(AdapterView父,视图v,int位置,长 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
,您始终可以选择添加一个附加密钥来设置初始列表中的未过滤位置。
如果您将自己的适配器与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
类。
请帮助我的朋友 – sarath 2012-07-18 04:06:36
海的朋友,我试图解决这个问题,但不能......我wonder.Why没有从Android老虎的解决方案??? – 2012-07-20 12:27:51