How to change start destination of a navigation graph programmatically [Jetpack]

前端 未结 7 1789
醉酒成梦
醉酒成梦 2020-12-08 00:30

Basically, I have the following navigation graph:

I want to change my starting point in navigation graph to fragment 2 right after reaching it

7条回答
  •  离开以前
    2020-12-08 00:51

    Okay, after messing with this for a bit I found a solution that worked for me that didn't require a ton of work.

    It appears two things MUST be in place for it function as if your secondFragment is your start destination.

    use the ALTERNATIVE option in the accepted post

    
    
         
    
    
    
    
    

    The above will remove firstFragment from the stack and inflate secondFragment when moving. The app cannot step back to firstFragment anymore BUT your left with secondFragment showing a back arrow as @szaske stated.

    This is what made the difference. I previously defined my AppBarConfig using the NavigationController.graph like so

    // Old code
    val controller by lazy { findNavController(R.id.nav_host_fragment) }
    val appBarConfig by lazy { AppBarConfiguration(controller.graph) }
    

    Updating it to define a set of top-level destinations rectified the issue of showing the back arrow on secondFragment instead of a hamburger menu icon.

    // secondFragment will now show hamburger menu instead of back arrow.
    val appBarConfig by lazy { AppBarConfiguration(setOf(R.id.firstFragment, R.id.secondFragment)) }
    

    Setting the start destination may or may not have negative implications in your project so do it as needed however in this example we do not need to do so. If it makes you warm and fuzzy to ensure that your graph has the correct start fragment defined, you can do it like so.

    controller.graph.startDestination = R.id.secondFragment
    

    Note: Setting this does not prevent the back arrow from occurring in secondFragment and from what I have found seems to have no effect on navigation.

提交回复
热议问题