Search code examples
androidandroid-jetpackandroid-architecture-navigation

Navigation graph hos in multi activity


I am new in using navigation component I have 2 activity each one have 3 fragments should I create for each activity a navigation host graph or there are a way to use only one nav graph for 2 activities?


Solution

  • For Navigation components with multiple-activities, you shouldn't start activities using Intents, instead, you need to add activities as destinations to the nav_graph.

    Should I create for each activity a navigation host graph or there are a way to use only one nav graph for 2 activities ?

    Yes you should, for n activities, you should have n nav graphs, or less (in case you need to make some activities like normal activities that are not involved in the navigation)

    So, in your case you have 2 activities, then you should have nav_grap1 & nav_grap2.

    And supposing you need to move from activity1, fragment1 to activity2, then what you need to do:

    • In nav_graph1 add <activity2> as a destination.
    • Create an action in nav_graph1 from fragment1 to activity2

    The nav graph of activity1 should look to something like:

    <?xml version="1.0" encoding="utf-8"?>
    <navigation xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/navigation"
        app:startDestination="@id/fragment1_1">
    
        <fragment
            android:id="@+id/fragment1_1"
            android:name="com.example.android.xx.Fragment1_1"
            android:label="Fragment1_1" >
    
            <action
                android:id="@+id/action_fragment1_1_to_secondActivity"
                app:destination="@id/secondActivity" />
    
        </fragment>
    
        <fragment
            android:id="@+id/fragment1_2"
            android:name="com.example.android.xx.Fragment1_2"
            android:label="Fragment1_2" />
    
        <activity
            android:id="@+id/secondActivity"
            android:name="com.example.android.xx.SecondActivity"
            android:label="SecondActivity" />
    
    </navigation>
    
    • Whenever you want to move to activity2, then just use the different navigate() methods of the navigationController; for instance:
    findNavController().navigate(R.id.action_fragment1_1_to_secondActivity)
    

    For more info check documentation, and check this question