如何实现上下文菜单Android上ListActivity?上下文、如何实现、菜单、ListActivity

2023-09-12 22:34:45 作者:花落浅殇

如何实现通过长按触发的上下文菜单或点击正在使用内置的布局和ListAdapter?

How do you implement a context menu triggered by a long click or tap on a ListActivity that is using the built in layouts and a ListAdapter?

推荐答案

在onCreate方法调用registerForContextMenu像这样的:

On the onCreate method call registerForContextMenu like this:

registerForContextMenu(getListView());

,然后填充在onCreateContextMenu(ContextMenu菜单,查看查看,ContextMenuInfo menuInfo)。该menuInfo参数可以提供有关哪些项目是长期的点击以这种方式:

and then populate the menu on onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo). The menuInfo argument can provide information about which item was long-clicked in this way:

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。

and when the user picks an option, onContextItemSelected is called. Also onMenuItemSelected and this fact is not explicitly explained in the documentation except to say that you use the other method to receive the calls from the context menu; just be aware, don't share ids.

在onContextItemSelected你可以得到阿霍德的MenuInfo的,因此该项目通过调用选择getMenuInfo():

On onContextItemSelected you can get ahold of the MenuInfo and thus the id of the item selected by calling getMenuInfo():

try {
    info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
} catch (ClassCastException e) {
    Log.e(TAG, "bad menuInfo", e);
    return false;
}
long id = getListAdapter().getItemId(info.position);