onCreateOptionsMenu 未被调用.工具栏显示,但为空,没有任何菜单和图标



我正在尝试在我的简单应用程序中使用工具栏。它显示但不显示我放置在菜单文件中的任何选项/图标。我的最低 sdk 是 16,我最近将我的项目迁移到了 androidX。onCreateOptionMenu 也没有被调用。if(getSupportActionbar((!=null( 块没有被调用,因为我在样式.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>

如果此代码在Fragment中,则需要在onCreate方法中调用setHasOptionsMenu(true)。这里进一步记录了它:https://developer.android.com/reference/androidx/fragment/app/Fragment.html#setHasOptionsMenu(布尔值(

你的问题是你使用的是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>

相关内容

最新更新