【Android】BottomNavigationView でナビゲーションアイテムのラベルを全て常時表示する方法

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

はじめに

テントの中から失礼します、IoT 事業部のてんとタカハシです!

Android アプリ開発初心者の私ですが、Android Studio の使い方やら専門用語になかなか慣れず、何かするたびに苦戦を強いられますが、なんとか頑張っています。

自作しているアプリに BottomNavigationView を導入してみたのですが、ナビゲーションアイテムをデフォルトの状態から1つ増やして計4つにすると、常時表示されるラベルは1つだけになってしまいました。ラベルの表示設定を変更して、全てのラベルを常時表示するための方法を本記事で紹介しようと思います。

環境

  • macOS Catalina v10.15.7
  • Android Studio 4.2.1
  • minSdkVersion 21

デフォルトの表示を確認する

まずは、BottomNavigationView を導入した際の表示を確認します。

Android プロジェクト作成時に「Bottom Navigation Activity」を選択します。

Android プロジェクトの作成が完了したら、そのままアプリを起動します。

デフォルトで、「Home」「Dashboard」「Notifications」の3つがナビゲーションアイテムとして実装された状態になっています。それぞれアイコンとラベルが全て表示されていることが確認できます。

ナビゲーションアイテム4つの表示を確認する

では、この状態から、ナビゲーションアイテムを1つ追加して計4つにしてみます。

すると、選択されているナビゲーションアイテムのラベル以外は非表示になることが確認できます。

ラベルを全て常時表示する

答えは LabelVisibilityMode の設定を追加してあげることで対応できました。

下記の通り BottomNavigationView のレイアウトにapp:labelVisibilityMode="labeled"を追加します。

app/src/main/res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="?attr/actionBarSize">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="?android:attr/windowBackground"
        app:labelVisibilityMode="labeled"   
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/nav_host_fragment_activity_main"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/nav_view"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>

アプリを起動すると、ナビゲーションアイテム4つ全てのラベルが表示されていることを確認できます。

どうもデフォルトの設定ではLABEL_VISIBILITY_AUTOになっているようで、ドキュメントの説明通り、

Label behaves as "labeled" when there are 3 items or less, or "selected" when there are 4 items or more.

ナビゲーションアイテムが3つ以下 or 4つ以上でラベルの表示設定が変わるような挙動みたいです。なるほど。

おわりに

ナビゲーションアイテムのラベルを全て常時表示できるようになりました。細かい設定ですが、初心者だと一体何を変えてあげれば良いのか全然わからなかったりして、結構ハマるポイント?な気がするので、同じようなことで困っている方の参考になると嬉しいです。

今回は以上になります。最後まで読んで頂きありがとうございました!