android - 不调用 onCreateOptionsMenu。工具栏显示但没有任何菜单和图标为空
问题描述
我正在尝试在我的简单应用程序中使用工具栏。它显示但不显示我放置在菜单文件中的任何选项/图标。我的最低 sdk 是 16,我最近将我的项目迁移到了 androidX。onCreateOptionMenu 也没有被调用。if(getSupportActionbar()!=null) 块没有被调用,因为我在 style.xml 中配置了 noActionBar。我不知道我错过了什么。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
androidx.appcompat.widget.Toolbar Toolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(Toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("My Title");
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
Log.i("onCreate", "menu");
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
<style name="HeaderBar">
<item name="android:background">#F3F5FF</item>
</style>
解决方案
你的问题是你正在使用一种NoActionBar
风格 enter code here
,那为什么onCreateOptionMenu
从来没有被调用过。将您的父基本主题更改为此
<style name="AppTheme" parent="@android:style/Theme.Holo.Light">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<!-- Customize your theme here. -->
</style>
推荐阅读
- c++ - 为什么我需要定义一个函数才能将其传递给不调用它的模板函数?
- javascript - 判断数组元素是代表对象还是值
- caching - 多级缓存中的一致性如何实现?
- elixir - 尝试在 iex 中运行:observer.start 时出现 wxmac elixir 错误
- node.js - 验证后无密码验证用户一次
- scikit-learn - 如何修复 sklearn.linear_model.LogisticRegression 中的一些系数
- python - 如何打印异步队列?
- java - 为什么从 JSP 中检索 servlet 的 init 参数时得到 null?
- python - 用户输入 Zip 文件
- javascript - React - 如何处理不同组件中输入的表单提交?