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

前端 未结 7 1792
醉酒成梦
醉酒成梦 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:45

    You don't really need to pop the Splash Fragment. It can remain there for the rest of your App life. What you should do is from the Splash Screen determine which next Screen to Show.

    In the picture above you can ask in the Splash Screen State if there is a saved LoginToken. In case is empty then you navigate to the Login Screen.

    Once the Login Screen is done, then you analyze the result save the Token and navigate to your Next Fragment Home Screen.

    When the Back Button is Pressed in the Home Screen, you will send back a Result message to the Splash Screen that indicates it to finish the App.

    Bellow code may help:

    val nextDestination = if (loginSuccess) {
        R.id.action_Dashboard
    } else {
        R.id.action_NotAuthorized
    }
    
    val options = NavOptions.Builder()
        .setPopUpTo(R.id.loginParentFragment, true)
        .build()
    
    findNavController().navigate(nextDestination, null, options)
    

提交回复
热议问题