I have below screen hierarchy [Activity1] -> [fragment1] -> [fragment2] -> [fragment3]
I have a deep-link which should open [Activity1] with [fragment3]. On back press, It should navigate to [fragment2] and further back press to [fragment1]
How can I achieve this without showing [fragment1] and [fragment2] before [fragment3] as creating [fragment1] and [fragment2] beforehand and adding it to back stack is an expensive job for me.


Doing it manually
You can detect the back button with
onBackPressed(), check if there is a fragment already in the stack usinggetBackStackEntryCount(), and if there is none, replacefragment3usingfragment2(without addingfragment3to 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:
https://developer.android.com/guide/navigation/navigation-principles