Search code examples
androidandroid-architecture-navigationandroid-safe-args

Navigate from fragment of one graph to fragment of another graph with bundle


I have two graphs nav_graph1.xml and nav_graph2.xml(in two different modules/lib)

I want to navigate from fragment1 to fragment2 with bundles. How do i achieve using navigation component?

nav_graph1.xml

<?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/nav_graph1"
    app:startDestination="@id/fragment1">
    <fragment
        android:id="@+id/C1_fragment"
        android:name="com.example.multiplenavigation.C_nav_graph.C1 "
        android:label="C1"
        tools:layout="@layout/fragment_C1">
        <action
            android:id="@+id/C1_to_C2_fragment"
            app:destination="@id/C2_fragment" />
    </fragment>
</navigation>

nav_graph2.xml

<?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/nav_graph1"
    app:startDestination="@id/fragment2">
    <fragment
        android:id="@+id/fragment2"
        android:name="com.example.multiplenavigation.C_nav_graph.C1 "
        android:label="C2"
        tools:layout="@layout/fragment_C2">
    </fragment>
</navigation>

enter image description here

Thanks in Advance,


Solution

  • First, create a nested navGraph by including the second graph in the first.

    Then, if your destination fragment is not the start fragment of the second graph you need to use Uri as shown here in this answer: navigate to a fragment from another graph without it being the start destination

    Since you can't pass a bundle with Uri navigation, to pass the bundle you need something like a method to set and get the bundle on your activity, setting bundle from first fragment and get it in onCreate of the second fragment.