Android Identify listView using onItemClick listener

我的未来我决定 提交于 2019-12-19 11:55:35

问题


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


回答1:


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
}



回答2:


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:


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

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

default:
  break;
}


来源:https://stackoverflow.com/questions/21878090/android-identify-listview-using-onitemclick-listener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!