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

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

    UPDATE:

    When you have nav graph like this:

    
         
    
    
    
    

    And you want to navigate to the second fragment and make it root of your graph, specify the next NavOptions:

    NavOptions navOptions = new NavOptions.Builder()
            .setPopUpTo(R.id.firstFragment, true)
            .build();
    

    And use them for the navigation:

    Navigation.findNavController(view).navigate(R.id.action_firstFragment_to_secondFragment, bundle, navOptions);
    

    setPopUpTo(int destinationId, boolean inclusive) - Pop up to a given destination before navigating. This pops all non-matching destinations from the back stack until this destination is found.

    destinationId - The destination to pop up to, clearing all intervening destinations.

    inclusive - true to also pop the given destination from the back stack.


    ALTERNATIVE:

    
     
    
    
    
    

    And then on your code:

    findNavController(fragment).navigate(
        FirstFragmentDirections.actionFirstFragmentToSecondFragment())
    

    Old answer

    Deprecated: The clearTask attribute for actions and the associated API in NavOptions has been deprecated.

    Source: https://developer.android.com/jetpack/docs/release-notes


    If you want to change your root fragment to fragment 2 (e.g. after pressing back button on fragment 2 you will exit the app), you should put the next attribute to your action or destination:

    app:clearTask="true"
    

    Practically it looks in a next way:

    
         
    
    
    
    

    I've added app:clearTask="true" to action.


    Now when you perform navigation from fragment 1 to fragment 2 use the next code:

    Navigation.findNavController(view)
            .navigate(R.id.action_firstFragment_to_secondFragment);
    

提交回复
热议问题