简体   繁体   中英

Navigation Architecture Component- Passing argument data to the startDestination with Fragment

I have a fragment A which contains this code:

<RelativeLayout 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:layout_width="match_parent"
    android:layout_height="match_parent">

    .......

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/children_container"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/layout_navigation" />

    .......

</RelativeLayout>

that start my fragment B . I would like to know how I can pass some argument from fragmentA and get in my fragmentB .

By reading this link but its talked about Activity A from Activity B.

I tried to remove this line from my FragmentContainerView

app:navGraph="@navigation/layout_navigation"

And in my fragmentA I added this following line:

val bundle = Bundle().apply {
    putString(KEY, "value")
}

NavHostFragment.create(R.navigation.layout_navigation, bundle)

In my fragment B , my arguments is null

Do you have any idea?

Open your navigation graph xml file and select a fragment that will receive some data. On the right side of your screen are the fragment attributes.

在此处输入图像描述

Select "Arguments" option and click +. Then enter arguments name, data type etc.

在此处输入图像描述

When you enter data in the dialog, click "Add".

Now open your "fragmentA" and init navController

val navController = Navigation.findNavController(view)

And navigate to your "fragmentB" with data in Bundle

view.findViewById<Button>(R.id.openB).setOnClickListener { // <==== YOUR CLICK LISTENER THAT NAVIGATE TO FRAGMENT B
                navController.navigate(
                    R.id.action_fragmentA_to_fragmentB, // <==== YOUR ACTION ID (you can find it in your navigation graph XML file)
                    Bundle().apply {
                        putString("KEY", "My data") // <==== YOUR KEY AND DATA(data type should be similar to what you specified when create arguments in navigation graph XML file)
                    }
                )
            }

Now go to "fragmentB".java or.kt file and receive data by key

val data = arguments?.getString("KEY")

Hope my answer helps you!!

You can also read this article => pass data between fragments in nav component

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM