0

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.

2 Answers2

0

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

Logain
  • 4,259
  • 1
  • 23
  • 32
0

Make nested graphs, where in each nested graph the HOME fragment will be put on the backstack. So of u make multiple nested graphes all their home destinations will be in your backstack when u call the deepest fragment.

enter image description here

Inside the "deeperlink" nested graph:

enter image description here

Execute Deeplink Navigation:

make_deep_nav_action.setOnClickListener {
     findNavController().createDeepLink().setDestination(R.id.deepLinkFragmentEnd).createPendingIntent().send()
}

-> Don't do crazy deep navigations... 1 or 2 on the backstack is probably enough before it gets messy.

Javatar
  • 2,518
  • 1
  • 31
  • 43