2
0

More than 3 years have passed since last update.

Jetpack Navigationで最初のフラグメントでも戻るための左矢印を表示する

Last updated at Posted at 2020-07-23

メイン画面から設定画面が呼ばれるアプリがあります。すべての画面をJetpack Navigationで作っていたのですが、理由あってJetpack Navigationの適用範囲を設定画面のみにしました。
そうなるとJetpack Navigation上でトップとなる画面でも、前の画面に戻るための左矢印を表示したくなります。

device-2020-07-24-060057.gif

現状のツールバー左矢印表示のためのコードはこのようになっています。
Jetpack Navigationのバージョンは2.3.0です。

SettingActivity.kt
class SettingActivity : AppCompatActivity() {

    private lateinit var appBarConfiguration: AppBarConfiguration

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_setting)
        setSupportActionBar(toolbar)

        val host = supportFragmentManager
                .findFragmentById(R.id.nav_host_fragment) as NavHostFragment
        val navController = host.navController
        appBarConfiguration = AppBarConfiguration.Builder(navController.graph).build()
        setupActionBarWithNavController(navController, appBarConfiguration)
    }

    override fun onSupportNavigateUp(): Boolean {
        return findNavController(R.id.nav_host_fragment).navigateUp(appBarConfiguration)
    }
}

検索してみたところ、Stackoverflowに答えがありました。
https://stackoverflow.com/questions/55951871/display-back-button-on-toolbar-on-first-screen-of-navigation-graph

AppBarConfigurationのインスタンス作成時の設定を変更するだけです。

SettingActivity.kt
appBarConfiguration = AppBarConfiguration.Builder(
        /* ここを空欄にすることで、左矢印を表示するトップレベルなフラグメントを
           開始フラグメント(ナビゲーショングラフxmlファイルのstartDestination属性)にしない */)
        .setFallbackOnNavigateUpListener {
            // Jetpack Navigationで左矢印を処理できないときの処理
            // このActiivtyを閉じる
            finish()
            // 左矢印が処理できたことを伝える
            true
        }.build()
2
0
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
2
0