5

NavController has methods navigate which navigate by default with backstack. How to navigate to the fragment without having backstack? Please note that, I am not asking about FragmentTransaction

Farrux Bahodirov
  • 358
  • 4
  • 12

2 Answers2

7

If you have a back stack of:

A -> B

And want to get to a back stack of

A -> C

You can do a 'replace' operation by popping B off the back stack and adding C.

In Navigation, this is done by using app:popUpTo (and optionally app:popUpToInclusive="true" if needed) to the <action> in your XML or by using the equivalent NavOptions API.

<action
  android:id="@+id/goToC"
  app:destination="@+id/c"
  app:popUpTo="@+id/b"
  app:popUpToInclusive="true"/>
ianhanniballake
  • 191,609
  • 30
  • 470
  • 443
1

You can do it like this:

val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
val navView: NavigationView = findViewById(R.id.nav_view)
val navController = findNavController(R.id.nav_host_fragment)

appBarConfiguration = AppBarConfiguration(
    setOf(
        R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
        R.id.nav_tools, R.id.nav_share, R.id.nav_send
    ), drawerLayout
)

setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)

navView.setNavigationItemSelectedListener {

    //----------- Pop Back Stack
    navController.popBackStack()
    //---------------------------

    navController.navigate(it.itemId)
    drawerLayout.closeDrawers()

    true
}
B-GangsteR
  • 2,534
  • 22
  • 34