I need to find out from which fragment the user switched to another fragment. I thought I should use the fragment name, but how do I get that name? Or is my method not very reliable and there are some other options?
P.S.: I use NavHostFragment
and Kotlin
1 Replies
Instead of the headache of tracking the former fragment with passed-in arguments, you'd apply previousBackStackEntry which returns a NavBackStackEntry
that is:
the previous visible entry on the back stack or null if the back stack has less than two visible entries
So, to get the id of the previous destination use: previousBackStackEntry?.destination?.id
For case, assume you've 3 fragments: fragment_a, fragment_b, and fragment_c. And at the fragment_c you need to know from which it's passed
To know the former scrap in fragment_c:
val previousFragment = findNavController().previousBackStackEntry?.destination?.id
previousFragment?.let {
when (previousFragment) {
R.id.fragment_a_id ->
// The previous fragment is Fragment a
R.id.fragment_b_id ->
// The previous fragment is Fragment b
else ->
// The previous fragment is neither Fragment a nor b
}
}