Search code examples
androidnavigationparent-childandroid-architecture-navigationandroid-jetpack-navigation

Jetpack Navigation: how to navigate from child of one nested graph to child from another nested graph?


Navigation structure:

MainActivity
|- nav_root
   |- HomeFragment
   |- AuthNestedGraph
   |  |- nav_auth
   |  |  |-BeforeOtpFragment(home)
   |  |  |-OtpFragment
   |
   |- ProfileNestedGraph
   |  |- nav_prfole
   |  |  |-ProfileFragmentOne(home)
   |  |  |-ProfileFragmentTwo

enter image description here enter image description here

I can navigate from HomeFragment to BeforeOtp(nav_auth home), toProfileOne(nav_profile home). Also i can navigate from any auth fragment to toProfileOne, or from profile fragments to BeforeOtp by global id

But how navigate to child fragment that is not set home from fragment at another nested graph/nav file? Like to OtpFragment/ProfileTwoFragment. How to change navcontroller?

When trying global i got an exception: "cannot be found from the current destination Destination"

I can do it by deeplinks but it is not solution im looking for.

This project github

enter image description here


Solution

  • Turned out that answer was pretty simple, but hope it can help someone.

    So, we want navigate from any Auth fragment from nav_auth to ProfileTwo from nav_profile. What we do:

    1. Add global action to Profile Two in nav_profile: enter image description here
        <action
        android:id="@+id/action_global_profileTwoFragment"
        app:destination="@id/profileTwoFragment"
        app:popUpTo="@id/profileTwoFragment"
        app:popUpToInclusive="true"
        app:launchSingleTop="false" />
    
    1. In navigate function we find navController. Set new Graph by id of navigation file, where is the needed fragment located. And navigate by global action:
        override fun routeToProfileTwoFragment() {
            val navController = fragment.findNavController()
            navController.setGraph(R.navigation.nav_profile)
            navController.navigate(R.id.action_global_profileTwoFragment)
        }
    
    
    1. Becouse graph was changed if we want navigate to main navigation graph(nav_root) we need changed it back when navigate(also add global action to home fragment):
        override fun routeMain() {
            val navController = fragment.findNavController()
            navController.setGraph(R.navigation.nav_root)
            navController.navigate(R.id.action_global_home)
        }
    

    Github project was updated

    enter image description here