39

您如何实现由长按或点击使用内置布局和 ListAdapter 的 ListActivity 触发的上下文菜单?

4

3 回答 3

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 以及所选项目的 id :

try {
    info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
} catch (ClassCastException e) {
    Log.e(TAG, "bad menuInfo", e);
    return false;
}
long id = getListAdapter().getItemId(info.position);
于 2009-01-12T20:09:37.320 回答
14

您还应该查看Activity.registerForContextMenu(View)

于 2009-01-13T07:15:55.650 回答
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;
}
于 2011-12-30T21:20:51.267 回答