更多背景信息:
一切始于一个令人沮丧的事实,即传递给onItemClick()的“position”值是无用的。这个“position”指的是数组被过滤后的位置,但我需要知道它的真实位置。因此,我尝试的做法是当我得到所选项目的文本(使用getItemAtPosition(position)),将其逐一与支撑ArrayAdapter的原始字符串数组进行比较。然而,我发现当onItemClick()被调用时,适配器已经被过滤了,我不再能够访问原始数组。所以,我想如果我能够移除过滤,也许我就可以重新获取原始数组,并在其中查找所选项目。
ArrayAdapter<String> mAdapter;
public void onCreate() {
// Create an adapter and remembere it as a class member.
mAdapter = new ArrayAdapter<String>(this, layoutId);
// Add 100 strings to it and attach it to an AutoCompleteTextView
for (int i = 0; i < 100; i++)
mAdapter.add("random text");
((AutoCompleteTextView)findViewById(id)).setAdapter(mAdapter);
}
@Override
public void onItemClick(AdapterView<?> actv, View view, int position, long id) {
if (actv.getAdapter().equals(mAdapter))
Log.d("The adapter contained in actv is the same one I created earlier.");
// And, I can get the text of the item the user selected
String selected = (String)actv.getItemAtPosition(position);
// However, although the adapter passed in is still the same one, but the
// number of items in it is only 1! Because the array has been filtered.
int numItems = actv.getAdapter.getCount();
// So, I'm thinking if I can somehow remove the filtering here, then I can
// get back those 100 items, and do a search like following:
for (int i = 0; i < actv.getAdapter.getCount(); i++)
if (selected == actv.getAdapter.getItem(i))
break; // Eureka!!!
}
解决获取所选项目的真实位置问题的方法:
是否有一种方法可以利用"id"值?比如,为每个项目分配一个id,然后希望onItemClick()会传回正确的id。
像我上面说的那样,删除过滤器(可能吗),恢复原始的100个项目,并逐个进行搜索。
这是最后的手段,我知道它会起作用,但我不想这样做:一旦我得到所选文本的文本,我就返回数据源(来自数据库)的源代码,查询那100个项目,并执行搜索。
另一个可怜的最后手段:为了避免在#3中再次访问数据库时的开销,在onCreate()中创建ArrayAdapter时,我使用自己的ArrayList来记住所有这些100个字符串。
我做错了吗?从AutoCompleteTextView获取所选项目的真实位置的“正确”方法是什么?
非常感谢!
(我在某个地方读到过,似乎是来自Google Android团队的某个人说应该使用getFirstVisiblePosition()来解决位置问题。但我无法弄清楚如何做到。)