我的活动中有两个使用相同的OnItemClickListener
ListViews
。有没有办法确定我现在正在按哪个ListViews
元素?我使用了以下代码:
@Override
public void onItemClick(AdapterView<?> list, View view, int position,
long id) {
if (view.getId() == R.id.listDictionary) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, WordActivity.class);
DictionaryListElement ele = (DictionaryListElement) dictionaryList
.getAdapter().getItem(position);
intent.putExtra("word", ele.getWord());
startActivity(intent);
} else if (view.getId() == R.id.listFavourites) {
Intent intent = new Intent(MainActivity.this, WordActivity.class);
String ele = (String)favouritesList.getAdapter().getItem(position);
intent.putExtra("word", ele);
startActivity(intent);
}
}
但它不起作用。我认为它获取的是每个按下元素的 id,而不是ListViews
您应该
使用 ListView
的 ID(此处ListView
作为AdapterView
传递给 onItemClick()
),而不是View
的 ID,因为此View
是ListView
项。
if(list.getId() == R.id.listDictionary) {
// item in dictionary list is clicked
} else if (list.getId() == R.id.listFavourites) {
// item in favourite list is clicked
}
如果将逻辑与 ifs 区分开来,为什么需要相同的侦听器?为每个视图创建单独的侦听器。这将是更干净的代码,也应该可以工作。
// dictionary listener
@Override
public void onItemClick(AdapterView<?> list, View view, int position,
long id) {
Intent intent = new Intent(MainActivity.this, WordActivity.class);
DictionaryListElement ele = (DictionaryListElement) dictionaryList
.getAdapter().getItem(position);
intent.putExtra("word", ele.getWord());
startActivity(intent);
}
// favorites listener
@Override
public void onItemClick(AdapterView<?> list, View view, int position,
long id) {
Intent intent = new Intent(MainActivity.this, WordActivity.class);
String ele = (String)favouritesList.getAdapter().getItem(position);
intent.putExtra("word", ele);
startActivity(intent);
}
switch(list.getId()){
case R.id.listDictionary:
//listDictionary related action here
break;
case R.id.listFavourites:
// listFavourites related action here
break;
default:
break;
}