我在创建 ListView 时遇到问题:我希望在单击某个项目时将其选中。
我的代码如下:
protected void onResume() {
...
ListView lv = getListView();
lv.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long id) {
Log.v(TAG, "onItemSelected(..., " + pos + ",...) => selected: " + getSelectedItemPosition());
}
public void onNothingSelected(AdapterView<?> adapterView) {
Log.v(TAG, "onNothingSelected(...) => selected: " + getSelectedItemPosition());
}
});
lv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long id) {
lv.setSelection(pos);
Log.v(TAG, "onItemClick(..., " + pos + ",...) => selected: " + getSelectedItemPosition());
}
});
...
}
当我运行它并单击例如第二项(即 pos=1)时,我得到:
04-03 23:08:36.994: V/DisplayLists(663): onItemClick(..., 1,...) => selected: -1
即,即使使用正确的参数调用 OnItemClickListener 并调用 setSelection(1),也没有选择项目(因此也永远不会调用 OnItemSelectedListener.onItemSelected(...) 并且 getSelectedItemPosition() 在setSelection(1)-调用。
我错过了什么?
迈克尔
PS.:我的列表确实有> = 2个元素......