Search code examples
androidkotlinandroid-jetpackandroid-jetpack-navigation

Android Is it possible to have multiple nav_graph files?


So I was using Jetpack navigation and the number of fragments kept growing up.

We can separate fragments in different navigation graph as described in this document

jetpack nav graph docs

Then I tried to put different nav graphs in different files because that felt more organized and readable file but I get the following error when I try to navigate to different nav_graph files.

nav_graph_start.xml

<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/nav_graph_start"
    app:startDestination="@id/splashScreen"
    tools:ignore="UnusedNavigation">

    <fragment
        android:id="@+id/splashScreen"
        android:name="com.timetoface.android.splash.SplashFragment"
        android:label="Login Fragment"
        tools:layout="@layout/fragment_splash">

        <action
            android:id="@+id/action_splash_to_login"
            app:destination="@id/nav_graph_auth"
            />
        <action
            android:id="@+id/action_splash_to_home"
            app:destination="@id/nav_graph_home"
            />
    </fragment>
</navigation>

nav_graph_auth.xml

<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/nav_graph_auth"
    app:startDestination="@id/emailLoginScreen"
    tools:ignore="UnusedNavigation">
................................
</navigation>

nav_graph_home.xml

<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/nav_graph_home"
    app:startDestination="@id/emailLoginScreen"
    tools:ignore="UnusedNavigation">
................................
</navigation>

navigation destination com.app.android:id/nav_graph_home referenced from action com.app.android:id/action_splash_to_home is unknown to this NavController

So,

Are multiple navigation graph files not supported yet?

Am I missing something that I should change?


Solution

  • First of all you can use include. Take a look this

    example: first_graph.xml

    <include app:graph="@navigation/second_graph" />
    

    then set action to included graph's id

     <action
            android:id="@+id/action_fragment_to_second_graph"
            app:destination="@id/second_graph" />
    

    Also you can use extension to use multiple graphs merged.

    Take a look to this

    Actually every activity should have it's own nav graph.