Android 导航如何在二级片段上添加导航向上按钮

Android Navigation How to Add Navigation Up button on 2nd level fragment

我正在使用导航图来托管我的片段。如何从 more_menu_help 添加返回按钮,以便返回到 nav_more?

见截图:

我尝试执行以下操作,但是后退箭头图标出现在 nav_payments、nav_benefits 和 nav_more 片段中。我只想将后退箭头添加到 more_menu_help:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)


    val navController = Navigation.findNavController(this, R.id.nav_host_fragment)
    nav_bar.setupWithNavController(navController)

    // Set up ActionBar
    setSupportActionBar(toolbar)
    setupActionBarWithNavController(this, navController, null)

    nav_bar.setupWithNavController(navController)

    supportActionBar?.setDisplayHomeAsUpEnabled(false)
    supportActionBar?.setDisplayShowHomeEnabled(false)
    supportActionBar?.setDisplayShowTitleEnabled(false)

}

查看福利屏幕。导航向上后退按钮箭头显示在这里,我不想要。

根据 Navigation UI documentation:

By default, the Navigation button is hidden when a user is at a top-level destination of a navigation graph and appears as an Up button in any other destination.

If you want to customize which destinations are considered top-level destinations, you can instead pass a set of destination IDs to the constructor, as shown below:

val appBarConfiguration = AppBarConfiguration(
    setOf(R.id.nav_home, R.id.nav_payments, R.id.nav_benefits, R.id.nav_more))

然后在调用 setupActionBarWithNavController 时传递那个 AppBarConfiguration 对象:

setupActionBarWithNavController(navController, appBarConfiguration)

请注意,因为您使用的是 ActionBar,所以在根据 ActionBar section:

覆盖 onSupportNavigateUp() 时,您还必须传递相同的 AppBarConfiguration 对象
override fun onSupportNavigateUp(): Boolean {
  val navController = findNavController(R.id.nav_host_fragment)
  return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}

因此您应该将 AppBarConfiguration 对象保持在 class 级别(而不是 onCreate().

中的局部变量