Search code examples
androidkotlinnavigationandroid-architecture-navigation

Android Navigation Component navigate between graphs


I've got two navigation graphs nav_graph_red and nav_graph_blue and two Activities ActivityRed and ActivityBlue.

In each navigation graph I have a flow with 3 Fragments. redFragmentOne,redFragmentTwo,redFragmentThree and blueFragmentOne,blueFragmentTwo,blueFragmentThree

Now I want to navigate from ActivityRed - redFragmentOne to the destination blueFragmentTwo.

Is there a way to accomplish this?

I tried it this way:

Navigation.findNavController(ActivityBlue.newInstance(),R.id.host_navigation).navigate(R.id.blueFragmentTwo)

Any suggestions?


Solution

  • Solution:

    Start Activity with intent and pass your destination as Intent extra.

     val blueIntent = Intent(requireActivity(), ActivityBlue::class.java)
     blueIntent.putExtra("navigationStartDestination", R.id.blueFragmentTwo)
     startActivity(blueIntent)
    

    In ActivityBlue onCreate -> get the intent extra and define navigation graph

        val startDestination = intent.getIntExtra("navigationStartDestination", 0)
    
        val navHostFragment = nav_host_fragment_blue as NavHostFragment
        val inflater = navHostFragment.navController.navInflater
        val graph = inflater.inflate(R.navigation.nav_graph_blue)
    
        graph.startDestination = startDestination
        navHostFragment.navController.graph = graph
    

    Important!:

    Remove navGraph="nav_graph_blue" in your layout xml of the ActivityBlue

    <fragment
        android:id="@+id/nav_host_fragment_blue"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintTop_toTopOf="parent" />