Search code examples
androidandroid-jetpack-navigation

Android Navigation Component jump a few steps in graph at once


I use navigation component, and I need to in certain situations navigate a few steps forward at once. For example FragmentA has direction to FragmentB and the later has direction to FragmentC. My goal is to in certain situations jump directly to FragmentC but have the normal navigation graph, so when user comes back from FragmentC he/she appears on FragmentB as if he appeared in FragmentC by one by one navigation.

I found that NavDeepLinkBuilder can solve my problem with the following:

            val pendingIntent = NavDeepLinkBuilder(context)
                .setGraph(R.navigation.my_graph)
                .addDestination(R.id.fragmentA_destination,
                .addDestination(R.id.fragmentB_destination)
                .setComponentName(MyActivity::class.java)
                .createPendingIntent()

            pendingIntent.send()

It actually does what I want but with 2 problems:

  1. It finishes the calling activity, and I don't know if I can prevent it from finishing it.
  2. This does not seem to be right at all, as PendingIntent is not designed to be used to navigate inside my own application, so what I do above seems to be a sort of hack.

So how else can I achieve the same result without using this PendingIntent mechanism?


Solution

  • Just call navigate() multiple times, first to fragment B, then to fragment C. This is in fact precisely how deep links are internally handled by the Navigation Component.