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.

4
  • Does this answer your question? Pass data back to previous fragment using Android Navigation Commented Jun 15, 2020 at 14:14
  • the question is the same, but there s no detailed or explained solution that may be used Commented Jun 15, 2020 at 14:24
  • findNavController().popBackStack(R.id.a_fragment, false) I think you can use this to achieve your goal Commented Jun 15, 2020 at 16:03
  • I use findNavController(...).navigateUp() to navigate to the previous fragment. Commented Jul 17, 2020 at 9:52

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.