如何通过长按或触发使用内置布局和ListAdapter的ListActivity实现上下文菜单?
在onCreate方法上调用registerForContextMenu,如下所示:
registerForContextMenu(getListView());
然后填充onCreateContextMenu上的菜单(ContextMenu菜单,View视图,ContextMenuInfo menuInfo).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添加菜单项:
menu.add(0, MENU_ITEM_ID, 0, R.string.menu_string);
当用户选择一个选项时,会调用onContextItemSelected.同样 onMenuItemSelected并且在文档中没有明确解释这个事实,只是说你使用其他方法从上下文菜单接收调用; 请注意,不要共享ID.
在onContextItemSelected上,您可以通过调用getMenuInfo()来获取MenuInfo的ahold,从而得到所选项的id :
try { info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); } catch (ClassCastException e) { Log.e(TAG, "bad menuInfo", e); return false; } long id = getListAdapter().getItemId(info.position);
您还应该查看Activity.registerForContextMenu(View).
listView = (ListView) findViewById(R.id.listpockets); registerForContextMenu(listView); public void onCreateContextMenu(android.view.ContextMenu menu, View v, android.view.ContextMenu.ContextMenuInfo menuInfo) { //AdapterContextMenuInfo info = (AdapterContextMenuInfo)menuInfo; menu.setHeaderTitle(getString(R.string.titleDelete)); menu.add(0, CommonUtil.CONTEXT_MENU__DELETE_ID, 0, getString(R.string.menuDelete)); }; @Override public boolean onContextItemSelected(MenuItem item) { if(item.getItemId() == CommonUtil.CONTEXT_MENU__DELETE_ID) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); long id = this.listView.getItemIdAtPosition(info.position); Log.d(TAG, "Item ID at POSITION:"+id); } else { return false; } return true; }