Tuesday, February 28, 2012

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



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;




No comments:

Post a Comment