3

My flow of fragment is like this

Main -> A -> B -> C ->A

In fragment c, it has a submit button which will return to A. When I press back button in A, I want it back to Main. But it return to fragment c instead.

In fragment C, I use this

 findNavController().navigate(R.id.action_c_to_a)

nav_graph.xml

 <fragment
        android:id="@+id/fragmentC"
        android:name="xxx"
        android:label="xxx">
        <action
            app:launchSingleTop="true"
            app:popUpTo="@+id/fragmentA"
            app:popUpToInclusive="true"
            android:id="@+id/action_c_to_a"
            app:destination="@id/fragmentA" />
    </fragment>
John Joe
  • 12,412
  • 16
  • 70
  • 135
  • Are you sure you have `A` in your stack, when you navigate to it? Your configuration is correctly setup and works as you want it to. – tynn Jun 30 '19 at 08:34
  • I understand what you want to do. But you should implement "Up" navigation, not "Back" in this case. User should be expecting back as back, not back as up. – Fung Jul 04 '19 at 06:30

4 Answers4

12

Why not pop up to fragment A? You could just call findNavController().popBackStack(R.id.fragmentA, false) instead of navigating with an action.

Alex H
  • 767
  • 8
  • 7
  • not working val action = CheckoutFragmentDirections.actionCheckoutFragmentToProductFragment() findNavController().navigate(action) –  Mar 01 '21 at 17:19
0

try to look at my complete solution with removing/killing fragment from backstack.

Navigation Component set transition animation programmatically

Kebab Krabby
  • 1,574
  • 13
  • 21
0

You can override the back button behavior to do this. Provide custom back navigation

Fung
  • 961
  • 1
  • 8
  • 17
0

The idea is to set a app:popUpTo without setting app:destination. Indeed, setting a app:destination will create a fragment and add it to the backstack which is not what you want.

To you can just remove :

app:destination="@id/fragmentA"

If you have this :

app:popUpTo="@+id/fragmentA"

And it will really pop the backstack until fragmentA

Mathieu de Brito
  • 2,536
  • 2
  • 26
  • 30