Navigation Architecture Component - Dialog Fragments

Leonardo Deleon picture Leonardo Deleon · May 13, 2018 · Viewed 30.8k times · Source

Is it possible to use the new Navigation Architecture Component with DialogFragment? Do I have to create a custom Navigator?

I would love to use them with the new features in my navigation graph.

Answer

MatPag picture MatPag · Mar 20, 2019

May 2019 Update:

DialogFragment are now fully supported starting from Navigation 2.1.0, you can read more here and here

Old Answer for Navigation <= 2.1.0-alpha02:

I proceeded in this way:

1) Update Navigation library at least to version 2.1.0-alpha01 and copy both files of this modified gist in your project.

2) Then in your navigation host fragment, change the name parameter to your custom NavHostFragment

<fragment
    android:id="@+id/nav_host_fragment"
    android:name="com.example.app.navigation.MyNavHostFragment"
    app:defaultNavHost="true"
    app:navGraph="@navigation/nav_graph"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/toolbar" />

3) Create your DialogFragment subclasses and add them to your nav_graph.xml with:

<dialog
    android:id="@+id/my_dialog"
    android:name="com.example.ui.MyDialogFragment"
    tools:layout="@layout/my_dialog" />

4) Now launch them from fragments or activity with

findNavController().navigate(R.id.my_dialog)

or similar methods.