Android使用onItemClick侦听器识别listView

时间:2014-02-19 10:43:22

标签: android listview onitemclicklistener onitemclick

我的活动中有两个ListViews使用相同的OnItemClickListener。有没有办法确定我现在要按哪个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

3 个答案:

答案 0 :(得分:1)

如果将逻辑与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);
        }

答案 1 :(得分:1)

您应该使用ListView的ID(此处ListView作为AdapterView传递给onItemClick()),而不是View的ID View 1}}是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
}

答案 2 :(得分:0)

switch(list.getId()){
case R.id.listDictionary: 
//listDictionary related action here
break;

case R.id.listFavourites:  
// listFavourites related action here
break;

default:
  break;
}