LoginSignup
1
1

More than 3 years have passed since last update.

Android Navigation Componentによる画面遷移時のToolbar

Last updated at Posted at 2019-11-28

はじめに

この記事ではNavigation Componentの基本的な使い方は記載していません。
Navigation Componentを使った画面遷移時のToolbarの処理に着目しています。

Activityが持つViewの処理をActivityに書く

Toolbarを表示する際、ほとんどの場合ホストとなるActivityがToolbarを持ちます。
その際、ゲストのFragmentでToolbarに関する処理を書くと

val toolbar = view.findViewById<Toolbar>(R.id.toolbar)
requireActivity().setSupportActionBar(toolbar)

となりますが、あまり書きたくないです。
Toolbarに限らずFloatingActionButtonなど、Activityが持つViewに関する処理の変更はFragmentに書かずに極力Activityに書き、正しく役割分担することにより保守性を高めたいです。

Navigation Componentによる画面遷移時も同様

Navigation Componentを使う場合に作成するActivityとFragmentも同様に正しく役割分担させたいです。
この記事ではNavigation Componentによる画面遷移時の、Activityが持つToolbarの処理に着目し、Activityに処理を書いています。
以下の項目について記載しています。

  • FragmentによってToolbarの処理を分岐
  • Fragment間の画面遷移時にToolbarに関するViewを変更

各種バージョン

コードを読みやすくするためにRxBindingを使っています。

  • Kotlin 1.3.60
  • Navigation Component 2.2.0-rc02
  • RxBinding 3.1.0

FragmentによってToolbarの処理を分岐

Navigation Componentを使っているActivityに、表示しているFragmentによってToolbarの戻るボタン押下時の処理を分岐させた例です。
現在のDestinationのID(navigationレイアウトのfragmentのID)に応じて処理を分岐させています。

MainActivity.kt
binding.toolbar
    .navigationClicks()
    .filter { navController.currentDestination != null }
    .subscribe {
        when (navController.currentDestination!!.id) {
            R.id.firstFragment -> finish()
            R.id.secondFragment -> navController.navigate(
                SecondFragmentDirections.secondToFirst()
            )
        }
    }

現在のDestinationがFirstFragmentの場合、Activityを終了(finish())します。
現在のDestinationがSecondFragmentの場合、FirstFragmentに遷移します。

Fragment間の画面遷移時にToolbarに関するViewを変更

NavControllerにはaddOnDestinationChangedListenerというDestinationの変更に関するListenerがあります。
これを利用し画面遷移時にToolbarにあるButtonのvisibilityを変更しています。

MainActivity.kt
navController.addOnDestinationChangedListener { _, destination, _ ->
    when (destination.id) {
        R.id.firstFragment -> binding.toolbarButton.visibility = View.GONE
        R.id.secondFragment -> binding.toolbarButton.visibility = View.VISIBLE
    }
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1