Search code examples
androidandroid-navigationandroid-navigation-graph

Ho to pass an argument from a fragment that stays in NavGraphA to a start destination fragment of NavGraphB?


I have a FragmentA that stays in NavigationGraphA and a FragmentB that stays in the start destination of NavigationGraphB. How can I pass "isControlled" argument from FragmentA to FragmentB?

My code below:

NavigationbGraphA.xlm

<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/flow_execution_pre"
    android:label="Pre-Execution Flow"
    app:startDestination="@id/step01">

    <fragment
        android:id="@+id/step01"
        android:name="wfm.in.enel.com.modulotecnico.utenza.flow01.step01.FragmentA"
        android:label="@string/search_position"
        tools:layout="@layout/flow01_step01">
        <action
            android:id="@+id/action_step01_to_step02"
            app:destination="@id/step02" />
        <action
            android:id="@+id/action_step01_to_flow_direct_service"
            app:destination="@+id/flow_direct_service" />
    </fragment>
</navigation>

NavigationGraphB.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/flow_direct_service"
    app:startDestination="@id/flow_03_step_01">
    <fragment
        android:id="@+id/flow_03_step_01"
        android:name="wfm.in.enel.com.modulotecnico.utenza.flow03.step01.FragmentB"
        android:label="@string/direct_service_activation"
        tools:layout="@layout/flow03_step_01">
        <argument android:name="isControlled"
            android:defaultValue="false"
            app:argType="boolean"/>
        <action
            android:id="@+id/action_flow_03_step_01_to_step10"
            app:destination="@id/step10" />
    </fragment>
</navigation>```

Solution

  • You can pass arguments between destinations with Bundle:

    val bundle = bundleOf("isControlled" to true)
    navController.setGraph(R.navigation.nav_graph_b, bundle)
    

    and retrieve these arguments like this

    val isControlled = arguments?.get("isControlled") ?: false