How can I jump to a fragment by pressing the back button?

Viewed 46

I need to help for this question on Android Studio.

How can I jump to an fragment by pressing the back button? We don't add any button. Just clicking the back button on an android phone.

For example:

  1. I am going from activity_main to fragment1
  2. I am going from fragment1 to fragment2
  3. When I press the back button, I want to jump to activity_main, not fragment1.
1 Answers

When you're adding to backstack your fragment1 provide some tag to it - addToBackStack(your_tag_here) After that you can call this function from your fragment3

supportFragmentManager.popBackStack(your_tag_here, 0)

You should also listen to onBackPressed() in your fragment, take a look at this response.

In the end, it will look like that:

requireActivity().onBackPressedDispatcher.addCallback {
    parentFragmentManager.popBackStack(your_tag_here, 0)
}
Related