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.
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()
And last but not the least If you are in activty class I mean not Fragment you can use this:
override fun onBackPressed() {
do what you need
if you leave this fun empty, back button would not work any more
}
I think second option is your fit