0

我的活动中有两个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

4

3 回答 3

1

如果您将逻辑与 if 区分开来,为什么需要相同的侦听器?为每个视图创建单独的侦听器。这将是更简洁的代码,并且应该也可以工作。

// 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);
        }
于 2014-02-19T10:46:31.723 回答
1

您应该使用ListView(这里ListView作为AdapterViewto传递onItemClick())的 ID,而不是View因为这View是一个ListView项目的 ID。

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
}
于 2014-02-19T10:50:25.767 回答
0
switch(list.getId()){
case R.id.listDictionary: 
//listDictionary related action here
break;

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

default:
  break;
}
于 2014-02-19T11:02:15.827 回答