onCreateContextMenu 未被调用

onCreateContextMenu is not being called

我正在使用以下代码生成 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 中显示的自定义 AdapterView 我之前的问题?另外,如果重要的话,我的 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。您需要在创建上下文菜单时膨胀视图。

@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);