Home > other >  How to navigate to existing Fragment from BackStack?
How to navigate to existing Fragment from BackStack?

Time:01-10

I have a bunch of fragments using a single activity as host.

My fragments are arranged like this,

Frag1 -> (Press Next) -> Frag2 -> (Press Next) -> Frag3 -> (Press Next) -> Frag4

In Frag1, I have a another button which will directly navigate to Frag4.

In Frag4, If I click back button it is currently going back to Frag1. But Here I want this to navigate to Frag3.

CodePudding user response:

If I got what you want correctly, You can use popUpTo in Pop Behavior in the right side of your host xml where you connect fragments and navigate fragments and set popUpTo to a fragment that you want

or

you can use this code to say where to go when back button pressed:

Note: you need to paste them in fragment class

requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner) {
            add your navigation destonation or do whatever you want 
        }

you have another option too.

You can use:

view?.findNavController().popBackStack()

I think second option is your fit

  •  Tags:  
  • Related