如何在Android上的ListActivity中实现上下文菜单?
你如何实现一个上下文菜单,通过长时间点击触发,或点击使用内置布局和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);
当用户select一个选项时, 调用onContextItemSelected 。 另外onMenuItemSelected ,这个事实在文档中没有明确的解释,除了说你使用其他方法从上下文菜单接收调用; 请注意,不要共享ID。
在onContextItemSelected上,你可以得到MenuInfo的ahold,从而得到通过调用getMenuInfo()select的项目的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; }