Andranik
Andranik

Reputation: 2849

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?

Upvotes: 1

Views: 928

Answers (2)

htafoya
htafoya

Reputation: 19283

I know the answer is valid, but just to expand a little bit on it, you will need to advance the steps from the origin fragment.

Keep in mind that if your navigation actions require parameters or navigation branches you'll have to manage those validations according to your app architecture.

if using safeArgs you can do:

with(findNavController()) {
    navigate(Fragment1Directions.actionTo2())
    navigate(Fragment2Directions.actionTo3(someParam))

    // use the correct path to maintain a correct back stack
    if(someValidation) {
        navigate(Fragment3Directions.actionTo4())
        navigate(Fragment4Directions.actionTo6())
    } else {
        navigate(Fragment3Directions.actionTo5())
        navigate(Fragment5Directions.actionTo6())
    }

    navigate(Fragment6Directions.actionTo7())
}

Upvotes: 1

ianhanniballake
ianhanniballake

Reputation: 200080

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.

Upvotes: 2

Related Questions