0

With Jetpack navigation, I have Fragment A->B->C->B, For fragment B's onCreate, How to check B come from A or back from C.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
David Guo
  • 1,749
  • 3
  • 20
  • 30

1 Answers1

1

You have to pass some data from framgent A->B or C->B.

As Example you can send integer value, or string or any other according to your requirement. I'm using integer for example

<fragment
android:id="@+id/flow_step_one_dest"
android:name="com.example.android.codelabs.navigation.FlowStepFragment"
tools:layout="@layout/flow_step_one_fragment">
<argument
    android:name="flowStepNumber"
    app:argType="integer"
    android:defaultValue="1"/>

<action...>
</action>

and Fragment A and C you can pass value like this

val flowStepNumberArg = 1
val action = FragmentADirections.nextAction(flowStepNumberArg) //For Fragment A
//val action = FragmentCDirections.nextAction(flowStepNumberArg) //For Fragment C
findNavController().navigate(action)

and inside Fragment B you can retrieve by this:

val safeArgs: FlowStepFragmentArgs by navArgs()
val flowStepNumber = safeArgs.flowStepNumber

If you have not added dependencies for safeArgs than you can add it to project level build.gradle

dependencies {
    classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$navigationVersion"
//...
}

And in app level build.gradle at top add this line

apply plugin: 'androidx.navigation.safeargs.kotlin'

If you need more understanding than check out Google's Codelab

Keyur Nimavat
  • 3,595
  • 3
  • 13
  • 19
  • I also wandering, if there are some code to check where the B come from. and don't update the navigation config file. – David Guo Sep 25 '20 at 00:59
  • This is the proper way to pass some data to Fragment B. You just have to pass Int value like 1 from A and 2 for C fragments. And than check with safeArgs inside Fragment B. What is issue if you have just add simple arguments inside Frgamnet B navigation file? – Keyur Nimavat Sep 25 '20 at 02:18
  • No issue. Actually I use your method to track the source. but seems too much navigation need to change. my app related with a work flow process, different case have different work flow, but they actually the same UI page. – David Guo Oct 12 '20 at 01:23
  • You do not need to change navigation, you just have to add arguments where you have used navigation only.There is other way to use ViewModel, if you know how to use ViewModel than you can use it. – Keyur Nimavat Oct 12 '20 at 01:33