'How to start the same action multiple times from the same startingDestination using navigation graph?

I started recently using the navigation graph and i have a problem that i havent solved yet. I want to open the same fragment multiple times that they are stacked on each other. I already figured out that i need Dialogfragment because otherwise the graph is doing a replace instead of add.

The problem is that i can call the action only once. When i try to call the same action twice i the app crashes: Caused by: java.lang.IllegalArgumentException: Navigation action/destination com.graphexample:id/action_add_fragment_2 cannot be found from the current destination Destination...

My Graph:

<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/nav_graph_stack"
    app:startDestination="@id/fragment_1">

    <fragment
        android:id="@+id/fragment_1"
        android:name="com.graphexample.view.Fragment1"
        android:label="fragment_label_1"
        tools:layout="@layout/fragment_1" >
        <action
        android:id="@+id/action_stack_fragment_2"
            app:destination="@id/fragment_2">
        </action>
    </fragment>

    <dialog
        android:id="@+id/fragment_2"
        android:name="com.graphexample.view.Fragment2"
        android:label="fragment_label_2"
        tools:layout="@layout/fragment_2">
    </dialog>
</navigation>

The Code in Fragment1:

  override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        (0..9).forEach {
            findNavController().navigate(R.id.action_stack_fragment_2)
        }
    }

When i try the same without the graph it works as intended:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    (0..9).forEach { i ->
        Fragment2().show(requireActivity().supportFragmentManager, "$i")
    }

}

Is there any way to archive startin the same activity multiple times from the same source using the navigation graph or do i have use the old way?



Solution 1:[1]

You can do this using self-action.

<action
            android:id="@+id/action_ fragment_2_self"
            app:destination="@id/fragment_2" />

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abdullah Javed