你如何在 Android 上的 ListActivity 中实现上下文菜单? [英] How do you implement context menu in a ListActivity on Android?

查看:31
本文介绍了你如何在 Android 上的 ListActivity 中实现上下文菜单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 menu, View view, 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:

and you add menu items in the usual way calling 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 上,您可以通过调用 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);

这篇关于你如何在 Android 上的 ListActivity 中实现上下文菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆