java - onCreateContextMenu 未被调用

标签 java android android-layout android-contextmenu

我使用以下代码生成onCreateContextMenu,但是,单击列表项时我没有收到任何响应。

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenu.ContextMenuInfo menuInfo) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
    int currentId = (int) info.id;
    menu.add(0, MENU_DELETE_ID, 0, "Delete");
}

稍后我将使用 currentId,但上面的代码不会导致弹出带有 Delete 一词的弹出窗口。

可能是因为我使用的是自定义AdapterView,如this answer所示我之前的问题?另外,如果重要的话,我的 MainActivity 正在扩展 AppCompatActivity

我检查了其他问题,例如这个问题 onCreateContextMenu isn't being called但我没有使用 onItemLongClickListener

最佳答案

没有足够的代码来理解这里到底出了什么问题。但我可能会建议在实现 ContextMenu 时注意一些常见错误。

您需要先注册上下文菜单。来自创建上下文菜单的开发人员文档 -

If your activity uses a ListView or GridView and you want each item to provide the same context menu, register all items for a context menu by passing the ListView or GridView to registerForContextMenu().

因此,您可能会考虑在 ListActivityonCreate 函数中执行类似的操作。

registerForContextMenu(getListView());

而且我在您的 onCreateContextMenu 中没有看到任何 MenuInflater。您需要在创建上下文菜单时膨胀 View 。

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
                                ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.context_menu, menu);
}

来自文档

MenuInflater allows you to inflate the context menu from a menu resource. The callback method parameters include the View that the user selected and a ContextMenu.ContextMenuInfo object that provides additional information about the item selected. If your activity has several views that each provide a different context menu, you might use these parameters to determine which context menu to inflate.

并且您可能必须为列表项实现长按监听器。因为它似乎仅适用于长点击事件。

When the registered view receives a long-click event, the system calls your onCreateContextMenu() method. This is where you define the menu items, usually by inflating a menu resource.

在这里您可以查看完整的implementation documentation 。希望有帮助!

更新

如果您不使用ListActivity,您应该无法调用getListView。在这种情况下,只需在注册列表的上下文菜单时传递 ListView 引用即可。

ListView lv = (ListView) findViewById(R.id.my_list);
registerForContextMenu(lv);

关于java - onCreateContextMenu 未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41560070/

相关文章:

java - 我应该在一个类中实现所有接口(interface)还是为每个接口(interface)创建一个类?

android - 使用覆盖 onclick 创建自定义控件

java - 应用程序显示与 Google 商店中的 Moto E 不兼容

java - 如何从 Android 中的文本输入框获取用户输入?

java - 在 Java 中将随机字符放置在数组板上

java - 二维数组和

android content activitynotfoundexception 没有找到处理 Intent 的 Activity - 当试图去 url

java - 如何使用固定宽高比 View 膨胀扩展 View

java - Java中的人脸识别

ImageView 尺度上的 Android 共享元素转换是错误的