首页 > 解决方案 > 如何将自定义菜单添加到底部应用栏?

问题描述

我在 android 中使用新的 Material Bottom 应用栏。我已经成功实现它,但我不知道如何将自定义菜单项添加到栏。每当我添加菜单项时,它们仅显示为 3 个点,即使我提供了选项 android:showAsAction="always"。

我想要特定的图标,如下面的屏幕截图。想要的结果 但相反,我得到了这样的结果。 在此处输入图像描述

这是布局代码。

<com.google.android.material.bottomappbar.BottomAppBar
    android:id="@+id/bottom_app_bar"
    style="@style/Widget.MaterialComponents.BottomAppBar"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_gravity="bottom"
    app:backgroundTint="@color/colorPrimaryDark"
    app:fabCradleMargin="5dp"
    app:fabAlignmentMode="center"/>

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_anchor="@id/bottom_app_bar" />

这是java代码。

BottomAppBar bottomAppBar = (BottomAppBar) findViewById(R.id.bottom_app_bar);
setSupportActionBar(bottomAppBar);

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.navigation, menu);
    return true;
}

菜单代码。

<item
    android:id="@+id/navigation_explore"
    android:icon="@drawable/explore"
    android:title="Explore"
    android:showAsAction="always"/>

<item
    android:id="@+id/navigation_profile"
    android:icon="@drawable/profile"
    android:title="Profile"
    android:showAsAction="always"/>

标签: androidmaterial-designandroid-bottomappbar

解决方案


经过这么多的研究,我终于找到了解决问题的方法。只需将“showAsAction”的命名空间从“android”更改为“app”即可。

<item
    android:id="@+id/navigation_explore"
    android:icon="@drawable/ic_search"
    android:title="Explore"
    app:showAsAction="always" />

推荐阅读