Question

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

Was it helpful?

Solution

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
}

OTHER TIPS

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);
        }
switch(list.getId()){
case R.id.listDictionary: 
//listDictionary related action here
break;

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

default:
  break;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top