菜单在应用程序的工具栏中可见,我可以打开它并查看菜单项,但是 onCreateOptionsMenu()
函数没有被调用,我通过设置断点知道这一点和调试,onOptionsItemSelected()
函数也是如此,它根本没有被调用。我看过其他关于相同问题的堆栈溢出帖子,但我似乎没有犯任何常见的错误。有谁知道问题是什么以及如何解决它?
MainActivity.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.menuItem1:
Toast.makeText(this, "menuItem1 selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.menuItem2:
Toast.makeText(this, "menuItem2 selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.menuItem3:
Toast.makeText(this, "menuItem3 selected", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menuItem1"
android:title="One"
app:showAsAction="never"/>
<item
android:id="@+id/menuItem2"
android:title="Two"
app:showAsAction="never"/>
<item
android:id="@+id/menuItem3"
android:title="Three"
app:showAsAction="never"/>
</menu>
编辑:
在 MainActivity.java 的 onCreate()
中,我有以下代码行:
toolBar.inflateMenu(R.menu.menu);
如果删除此行,工具栏中的菜单就会消失。不知道这是否有帮助或与我的问题有什么关系,但只是发布出来让你知道。
最佳答案
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
关于java - 显示菜单但未调用 onCreateOptionsMenu(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60524408/