メイン画面から設定画面が呼ばれるアプリがあります。すべての画面をJetpack Navigationで作っていたのですが、理由あってJetpack Navigationの適用範囲を設定画面のみにしました。
そうなるとJetpack Navigation上でトップとなる画面でも、前の画面に戻るための左矢印を表示したくなります。
現状のツールバー左矢印表示のためのコードはこのようになっています。
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()