0

I know the Android developer articles about Android Navigation:

https://developer.android.com/guide/navigation/navigation-pass-data

and

https://developer.android.com/guide/navigation/navigation-getting-started

Neither of the articles describes how to set the values of the arguments defined in the NavGraph.xml in the source fragment and how to retrieve them in the destination fragment? Could you give me a hint?

I also know the method Navigation.createOnClickListener(int ID, Bundle args) to set an OnClickListener to a button to navigate to a different destination. But the bundle args isn't the same type of arguments I defined in NavGraph.xml. Isn't it?

Peter
  • 579
  • 2
  • 7
  • 18

1 Answers1

0

At first, you need to add the argument like this into your navgraph.xml

<fragment
    android:id="@+id/score_destination"
    android:name="com.example.android.guesstheword.screens.score.ScoreFragment"
    android:label="destination_fragment"
    tools:layout="@layout/destination_fragment">
    <action
        android:id="@+id/action_restart"
        app:destination="@+id/game_destination"
        app:enterAnim="@anim/slide_in_right"
        app:exitAnim="@anim/slide_out_left"
        app:popEnterAnim="@anim/slide_in_right"
        app:popExitAnim="@anim/slide_out_lef />
    <argument
        android:name="score"
        android:defaultValue="0"
        app:argType="integer" />
</fragment>

Then, you have to send the argument from your source fragment like this:

findNavController(this).navigate(SourceFragmentDirections.actionSourceToDestination(argument))

And at last, you can retrieve the argument from your destination fragment:

DestinationFragmentArgs.fromBundle(arguments!!).score

In the upper example, I sent an int typed argument name score. You can send any kind of argument like this. If your argument is not a primitive type, you can also send that argument by creating a Parcelable model class.

I would be happy to provide you with any additional information. Thank you :)

Abir Hossain
  • 111
  • 7
  • Ok, maybe I didn't get it. According to the Android developer guide I thought there are four ways to pass data between destinations: 1. Using the viewmodel 2. Using a bundle 3. Using the gradle plugin 4. Defining arguments in the navgraph.xml. Isn't your solution using the gradle plugin? I would like to use number 4. Could it be that I have mistaken it? So there are only three ways and number 3 and 4 are the same? – Peter Jun 14 '19 at 09:41