0

I'm using a navigation graph to host my fragments. How do I add back button from more_menu_help so that it can go back to nav_more?

See screenshot: enter image description here

I tried to do the following, however, the back arrow icon appears in nav_payments, nav_benefits, and nav_more fragments. I just want to add back arrow to the 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)

}

See the benefits screen. The navigation up back button arrow shows up here, which I do not want. enter image description here

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
nsutanto
  • 93
  • 3
  • 9

1 Answers1

0

As per the 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))

Then pass that AppBarConfiguration object when you call setupActionBarWithNavController:

setupActionBarWithNavController(navController, appBarConfiguration)

Note that because you're using an ActionBar, you must also pass that same AppBarConfiguration object when overriding onSupportNavigateUp() as per the ActionBar section:

override fun onSupportNavigateUp(): Boolean {
  val navController = findNavController(R.id.nav_host_fragment)
  return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}

So you should keep your AppBarConfiguration object at the class level (rather than a local variable in onCreate().

Community
  • 1
  • 1
ianhanniballake
  • 191,609
  • 30
  • 470
  • 443
  • Thanks. It works. I tried this code before, but the only things that I did wrong were: val appBarConfiguration = AppBarConfiguration( setOf(R.id.nav_home, R.id.nav_payments, R.id.nav_benefits, R.id.nav_more)) I put the the fragment layout instead of the navigation id. – nsutanto Oct 25 '19 at 17:47