setSupportActionBar удаляет пункты меню

#java #android #android-toolbar

#java #Android #android-панель инструментов

Вопрос:

Прошу прощения, если я недостаточно четко объясняю проблему, с которой я столкнулся.

У меня есть проект, который использует MaterialToolbar, он ссылается на menu.xml из-за его внешнего вида. В меню есть потенциальные значки, которые я хочу использовать (избранное, удалить и т.д.).

Однако в моем коде при инициализации setSupportActionBar() он переопределяет заданную мной ссылку, значки больше не отображаются, кроме значка навигации.

Мне требуется setSupportActionBar() для моего проекта, есть ли способ, который я могу сохранить, setSupportActionBar() сохраняя внешний вид top_app_bar.xml ? Или, по крайней мере, значок, инициализированный в пункте меню?

activity_main_menu.xml

 <com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <com.google.android.material.appbar.MaterialToolbar
        android:id="@ id/topAppBar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:menu="@menu/top_app_bar"
        app:navigationIcon="@drawable/ic_menu_24dp"
        style="@style/Widget.MaterialComponents.Toolbar.Primary"/>
</com.google.android.material.appbar.AppBarLayout>
  

top_app_bar.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/delete"
        android:icon="@drawable/ic_delete_24dp"
        android:title="test"
        app:showAsAction="ifRoom"
        />
</menu>

<?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/delete"
        android:icon="@drawable/ic_delete_24dp"
        android:title="test"
        app:showAsAction="ifRoom"
        />
</menu>
  

MainMenu.java

 MaterialToolbar topAppBar = findViewById(R.id.topAppBar);
setSupportActionBar(topAppBar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
  

Ответ №1:

Это ожидаемое поведение. Когда вы устанавливаете панель действий на Activity роль Activity заключается в том, чтобы решить, какое меню будет отображаться.

Вот документация и объявление метода зависимости setSupportActionBar от appcompat-1.0.0 . Вы можете прочитать все это, но я явно выбрал одно предложение из java-doc и упомянул его под этим фрагментом.

 /**
 * Set a {@link Toolbar} to act as the {@link ActionBar} for this delegate.
 *
 * <p>When set to a non-null value the {@link #getSupportActionBar()} ()} method will return
 * an {@link ActionBar} object that can be used to control the given toolbar as if it were
 * a traditional window decor action bar. The toolbar's menu will be populated with the
 * Activity's options menu and the navigation button will be wired through the standard
 * {@link android.R.id#home home} menu select action.</p>
 *
 * <p>In order to use a Toolbar within the Activity's window content the application
 * must not request the window feature
 * {@link AppCompatDelegate#FEATURE_SUPPORT_ACTION_BAR FEATURE_SUPPORT_ACTION_BAR}.</p>
 *
 * @param toolbar Toolbar to set as the Activity's action bar, or {@code null} to clear it
 */
public abstract void setSupportActionBar(@Nullable Toolbar toolbar);
  

Акцент делается на этом предложении:

  * ... The toolbar's menu will be populated with the
 * Activity's options menu and the navigation button will be wired through the standard
 * {@link android.R.id#home home} menu select action ...
  

Это означает, что вам нужно переопределить onCreateOptionsMenu метод, чтобы создать меню в действии для панели действий:

 @Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.resource_id, menu);
    return true;
}
  

По умолчанию, если вы не переопределите этот метод, меню будет заполнено

… со стандартными пунктами системного меню.

Источник цитаты (обратите внимание, я удалил объяснения из java-doc onCreateOptionsMenu , которые не имеют отношения к этой проблеме):

 /**
 * Initialize the contents of the Activity's standard options menu.  You
 * should place your menu items in to <var>menu</var>.
 *
 * <p>This is only called once, the first time the options menu is
 * displayed.
 *
 * <p>The default implementation populates the menu with standard system
 * menu items. 
 *
 * @param menu The options menu in which you place your items.
 *
 * @return You must return true for the menu to be displayed;
 *         if you return false it will not be shown.
 */
public boolean onCreateOptionsMenu(Menu menu) {
    if (mParent != null) {
        return mParent.onCreateOptionsMenu(menu);
    }
    return true;
}
  

Комментарии:

1. Похоже, это решило мой вопрос, спасибо. Я ценю это.