Android Identify Listview Using Onitemclick Listener
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 pub
Solution 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
} elseif (list.getId() == R.id.listFavourites) {
// item in favourite list is clicked
}
Solution 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@OverridepublicvoidonItemClick(AdapterView<?> list, View view, int position,
long id) {
Intentintent=newIntent(MainActivity.this, WordActivity.class);
DictionaryListElementele= (DictionaryListElement) dictionaryList
.getAdapter().getItem(position);
intent.putExtra("word", ele.getWord());
startActivity(intent);
}
// favorites listener@OverridepublicvoidonItemClick(AdapterView<?> list, View view, int position,
long id) {
Intentintent=newIntent(MainActivity.this, WordActivity.class);
Stringele= (String)favouritesList.getAdapter().getItem(position);
intent.putExtra("word", ele);
startActivity(intent);
}
Solution 3:
switch(list.getId()){
case R.id.listDictionary:
//listDictionary related action herebreak;
case R.id.listFavourites:
// listFavourites related action herebreak;
default:
break;
}
Post a Comment for "Android Identify Listview Using Onitemclick Listener"