在 onCreate 方法调用上注册上下文菜单 http://developer.android.com/reference/android/app/Activity.html#registerForContextMenu(android.view.View)像这样:
registerForContextMenu(getListView());
然后填充菜单onCreateContextMenu(ContextMenu菜单,View视图,ContextMenuInfo menuInfo) http://developer.android.com/reference/android/app/Activity.html#onCreateContextMenu(android.view.ContextMenu,%20android.view.View,%20android.view.ContextMenu.ContextMenuInfo)。 menuInfo 参数可以通过以下方式提供有关长按哪个项目的信息:
AdapterView.AdapterContextMenuInfo info;
try {
info = (AdapterView.AdapterContextMenuInfo) menuInfo;
} catch (ClassCastException e) {
Log.e(TAG, "bad menuInfo", e);
return;
}
long id = getListAdapter().getItemId(info.position);
然后您以通常的方式添加菜单项menu.add http://developer.android.com/reference/android/view/Menu.html#add(int,%20int,%20int,%20java.lang.CharSequence):
menu.add(0, MENU_ITEM_ID, 0, R.string.menu_string);
当用户选择一个选项时,onContextItemSelected 事件 http://developer.android.com/reference/android/app/Activity.html#onContextItemSelected(android.view.MenuItem)叫做。还选定菜单项 http://developer.android.com/reference/android/app/Activity.html#onMenuItemSelected(int,%20android.view.MenuItem)文档中没有明确解释这一事实,只是说您使用其他方法从上下文菜单接收调用;请注意,不要共享 ID。
在 onContextItemSelected 上,您可以通过调用获取 MenuInfo 以及所选项目的 id获取菜单信息() http://developer.android.com/reference/android/view/MenuItem.html#getMenuInfo():
try {
info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
} catch (ClassCastException e) {
Log.e(TAG, "bad menuInfo", e);
return false;
}
long id = getListAdapter().getItemId(info.position);