如何实现通过长按或触发使用内置布局和ListAdapter的ListActivity触发的上下文菜单?
答案 0 :(得分:74)
在onCreate方法上调用registerForContextMenu,如下所示:
registerForContextMenu(getListView());
然后填充onCreateContextMenu(ContextMenu menu, View 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);
答案 1 :(得分:14)
答案 2 :(得分:5)
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;
}