Takuji->find;

株式会社はてなでアプリケーションエンジニアやってます、技術的な記事を書いているつもり

Support Library 25.0.0 で追加されたBottomNavigationViewを使ってみる #関モバ

こんばんは、 id:takuji31 です。

今日はSupport Library 25.0.0 で追加されたBottomNavigationViewを使ってみたので紹介します。

※これは本日開催の関西モバイルアプリ研究会 #19 で発表した内容です。

Bottom navigation について

Botton navigationは Material Designコンポーネントの一つで、Botton navigation patternを実現するために使います。

Bottom navigation - Components - Material design guidelines

上記のページに

Bottom navigation bars make it easy to explore and switch between top-level views in a single tap.

とあるので、だいたいiOSUITabBarを使ったナビゲーションと同じようなパターンを作る時に使えます。

このBotton navigationはある日突然ガイドラインに出現し、毎度のごとく実装はないからお前ら頑張れよって感じのスタンスでしたが、先日(2016/10/19)Support Library Libraryの25.0.0のリリースにサラっと含まれてました。

BottomNavigationView を使ってみる

Botton navigationの実装であるSupport LibraryのBottomNavigationViewを使ってみましょう。

BottomNavigationViewはDesign Support Libraryに含まれています。

build.gradleに依存を追加して

dependencies {
    compile 'com.android.support:design:25.0.0'
}

レイアウトにBottomNavigationViewを置きます。

<RelativeLayout>
    <android.support.design.widget.BottomNavigationView
        app:menu="@menu/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</RelativeLayout>

ナビゲーションのそれぞれの項目はAndroidのmenu形式のxmlで定義します。

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/menu_home"
        android:icon="@drawable/ic_home_black_24dp"
        android:title="Home"/>
    <item
        android:id="@+id/menu_notifications"
        android:icon="@drawable/ic_notifications_black_24dp"
        android:title="Notifications"/>
    <item
        android:id="@+id/menu_profile"
        android:icon="@drawable/ic_person_black_24dp"
        android:title="Profile"/>
</menu>

あとはActivityでListenerを設定するだけ。

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_bottom_navigation_view)
    bottomNavigationView.setOnNavigationItemSelectedListener {
        textView.text = "This is " + it.title.toString()
        true
    }
}

f:id:takuji31:20161026184157p:plain

べんり!

使ってみて

  • menuのxml書くだけでそれっぽいのができあがって便利
  • アイコンはToolbarなんかと同じようにtintingされる
  • 5件までしか置けない、それ以上置いたら例外
  • 3件とそれ以上でメニュー自体の見た目が違う
    • 3件の時はテキスト付きで等間隔表示
    • 4件以上の時は非アクティブなものはテキスト非表示、選択されたものが広がって表示
  • 切り替え時にアニメーションするんだけど、なんか違う
  • API25まだPreviewなので使うと本体のソースコードが見えない

おもてたんとちがう!感が若干ありもしつつ、便利なので普通に使えそうでした。

サンプルコードはこちら

github.com