How do you implement context menu in a ListActivity on Android?
Solution 1:
On the onCreate method call registerForContextMenu like this:
registerForContextMenu(getListView());
and then populate the menu on onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo). The menuInfo argument can provide information about which item was long-clicked in this way:
AdapterView.AdapterContextMenuInfo info;
try {
info = (AdapterView.AdapterContextMenuInfo) menuInfo;
} catch (ClassCastException e) {
Log.e(TAG, "bad menuInfo", e);
return;
}
long id = getListAdapter().getItemId(info.position);
and you add menu items in the usual way calling menu.add:
menu.add(0, MENU_ITEM_ID, 0, R.string.menu_string);
and when the user picks an option, onContextItemSelected is called. Also onMenuItemSelected and this fact is not explicitly explained in the documentation except to say that you use the other method to receive the calls from the context menu; just be aware, don't share ids.
On onContextItemSelected you can get ahold of the MenuInfo and thus the id of the item selected by calling getMenuInfo():
try {
info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
} catch (ClassCastException e) {
Log.e(TAG, "bad menuInfo", e);
return false;
}
long id = getListAdapter().getItemId(info.position);
Solution 2:
You should also look at Activity.registerForContextMenu(View).