Android 识别列表使用 onItemClick 侦听器查看



我的活动中有两个使用相同的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,因为此ViewListView项。

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;
}

相关内容

  • 没有找到相关文章

最新更新