0

I have 4 Fragments , A, B,C.Fragment A will be the main Fragment, I will be navigating from fragment A to Fragment B then Fragment B return with a result to fragment A. Then I will navigate To fragment C from fragment A, and fragment c will do some operations and return a result to fragment A. Each time the fragment A will show and keep the result returned from each fragment

The navigation between fragment A to the other fragment is implemented using this code

val bundle = Bundle()
bundle.putBoolean("data", true)
findNavController().navigate(R.id.myAction, toVoicePassphraseRecognitionbundle)

My problem her is that to return to fragment A, i also use findNavController().navigate()but doing so will create a new fragment that will be added to the stack, so my question is how can i navigate back from fragment B to A, or C to A while keeping the view state as it is without creating a new Fragment A.

Firas Chebbah
  • 415
  • 2
  • 12
  • 24
  • Does this answer your question? [Pass data back to previous fragment using Android Navigation](https://stackoverflow.com/questions/56243119/pass-data-back-to-previous-fragment-using-android-navigation) – EraftYps Jun 15 '20 at 14:14
  • the question is the same, but there s no detailed or explained solution that may be used – Firas Chebbah Jun 15 '20 at 14:24
  • findNavController().popBackStack(R.id.a_fragment, false) I think you can use this to achieve your goal – Sneha Sarkar Jun 15 '20 at 16:03
  • I use `findNavController(...).navigateUp()` to navigate to the previous fragment. – Ziem Jul 17 '20 at 09:52

1 Answers1

0

The problem is, you are setting Fragment A as destination in your action, what it does is, it creates a new instance of the Fragment.

What you really want is to go back to, not go to.

So what we we do to go back, we pop our back stack.

 <fragment
    android:id="@+id/fragmentC"
    android:name="com.sample.project.FragmentC"
    android:label="FragmentC">
    <action
        android:id="@+id/navigate_C_to_A"
        app:popUpTo="@+id/fragmentA"
        app:popUpToInclusive="false" />
</fragment>

popUpTo is where you want to land

popUpToInclusive means do you want this fragment to pop from stack too?

And let say your flow is like A->B->C->A

But Fragment A is unknown, or B and C are the part of flow that can be used at many places, so the A will not be A every time.

In that case :

<fragment
    android:id="@+id/fragmentC"
    android:name="com.sample.project.FragmentC"
    android:label="FragmentC">
    <action
        android:id="@+id/navigate_C_to_before_B"
        app:popUpTo="@+id/fragmentB"
        app:popUpToInclusive="true" />
</fragment>

popUpToInclusive is the key here

Himanshu Bansal
  • 139
  • 1
  • 5