首页 > 解决方案 > 不调用 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>

标签: androidandroid-toolbarandroidx

解决方案


你的问题是你正在使用一种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>

推荐阅读