Juri Strumpflohner
Juri Strumpflohner Juri is a full stack developer and tech lead with a special passion for the web and frontend development. He creates online videos for Egghead.io, writes articles on his blog and for tech magazines, speaks at conferences and holds training workshops.

HowTo: Get the selected list index on Android Activity from context menu event

1 min read

Consider the situation where you have an Activity displaying a list of items. You have a context menu and a normal option menu. When pressing the option menu button, you can get the selected item and index as follows:
//the selected index
int index = listView.getSelectedItemPosition();

//selected item
Object selObj = listView.getSelectedItem();
It is as simple as that. If you registered a context menu on the list, then the situation changes slightly and the "getSelectedItemPosition()" will fail. Instead, you have to do something like this
AdapterView.AdapterContextMenuInfo menuInfo;
menuInfo = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
int index = menuInfo.position;

Questions? Thoughts? Hit me up on Twitter
comments powered by Disqus