How to navigate fragment without adding it into backstack with NavController?

守給你的承諾、 提交于 2021-02-08 12:00:56

问题


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


回答1:


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"/>



回答2:


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
}


来源:https://stackoverflow.com/questions/53818362/how-to-navigate-fragment-without-adding-it-into-backstack-with-navcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!