12

How can I pass argument to dialog fragment using the navigation architecture component safeargs? below is my current implementation

Start Fragment

val navController = findNavController()
val action =
            QuestionListFragmentDirections.actionQuestionListFragmentToCustomDialogFragment(args.templateFlag)
        navController.navigate(
            action
        )

Destination Fragment

   args.templateFlage //supposed to return a boolean value 
   //but throws java.lang.IllegalStateException: Fragment QuestionTypeDialogFragment{e8be5e1} 
   (47b305ea-35b2-49e0-b378-d31a08ba9a41) QuestionTypeDialogFragment} has null arguments
Ismail
  • 445
  • 1
  • 5
  • 20

3 Answers3

19

May be you use args before fragment got it. For example I changed it in my code:

 private val args by navArgs<RadioDetailFragmentArgs>()
 private val stations = args.stations.toList()

with

private val args by navArgs<RadioDetailFragmentArgs>()
private val stations by lazy {
    args.stations.toList()
}

And it works

-2

Check out the instructions on passing data between destinations:

In your navigation graph add an entry for the Dialog Fragment.

<dialog
        android:id="@+id/questionListFragment"
        android:name="com.path.to.my.QuestionListFragment"
        android:label="Question List"
        tools:layout="@layout/layout_of_fragment">

          <argument
                android:name="ArgName"
                android:defaultValue="@null"
                app:argType="boolean"
                app:nullable="true" />

    </dialog>

Then in declaration of the Fragment that can initiate navigation to this Dialog fragment you will need to add an action:

    <action
        android:id="@+id/actionQuestionListFragmentToCustomDialogFragment"
        app:destination="@id/chooseVideo"
      />

Finally in the fragment that initiates navigation you can call the function navigate:

val directions = QuestionListFragmentDirections.actionQuestionListFragmentToCustomDialogFragment(args.templateFlag)
findNavigationController().navigate(directions)

Note that the argument of QuestionListFragment we've set android:defaultValue="@null" which means that the boolean value can be null. If this is not the case then you will need to remove it.

Marco RS
  • 8,145
  • 3
  • 37
  • 45
-4

You may send the parameter with a bundle instead of directions.

val bundle = Bundle()
bundle.putBoolean("templateFlag", args.templateFlag)

findNavController().navigate(
    R.id.action_QuestionListFragment_to_CustomDialogFragment,
    bundle
)
bkaancelen
  • 163
  • 2
  • 11