我使用以下代码生成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
orGridView
and you want each item to provide the same context menu, register all items for a context menu by passing theListView
orGridView
toregisterForContextMenu()
.
因此,您可能会考虑在 ListActivity
的 onCreate
函数中执行类似的操作。
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 theView
that the user selected and aContextMenu.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/