Doing it manually
You can detect the back button with onBackPressed()
, check if there is a fragment already in the stack using getBackStackEntryCount()
, and if there is none, replace fragment3
using fragment2
(without adding fragment3
to the backstack).
Repeat this for fragment1
. You'll probably want to architecture your navigation in a way that this doesn't look like a hack. Basically, if you are on a non-root fragment on the navigation tree but the back stack is empty, manually replace the fragment.
Using a library
If instead of writing the solution yourself you prefer some standard library to handle it for you, then Jetpack Navigation is the official option you might want to check.
As per the documentation:
The Navigation component supports deep linking and recreates a
realistic back stack for you when linking to any destination in your
navigation graph.
https://developer.android.com/guide/navigation/navigation-principles