Android Identify listView using onItemClick listen

2019-02-21 01:49发布

I have two ListViews in my activity that uses same OnItemClickListener. Is there any way to identify which ListViews element I am pressing now? I have used this code:

@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);

    }
}

But it is not working. I think it is getting id of each pressed element not ListViews

3条回答
男人必须洒脱
2楼-- · 2019-02-21 02:09

Why would you need the same listener if you distinguish logic with ifs? Create separate listeners for each view. It would be cleaner code and should work as well.

// 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);
        }
查看更多
放荡不羁爱自由
3楼-- · 2019-02-21 02:16
switch(list.getId()){
case R.id.listDictionary: 
//listDictionary related action here
break;

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

default:
  break;
}
查看更多
4楼-- · 2019-02-21 02:26

You should use the ID of ListView (here ListView is passed as AdapterView to onItemClick()), not the ID of View as this View is a ListView item.

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
}
查看更多
登录 后发表回答