Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out what the previous fragment was using the navigation component

I am trying to find out what the previous fragment was in the backstack and if it is the one that I want, then go back to that otherwise go to a different fragment. I am having problems finding out the name/id of my previous fragment. My current setup is as follows:

Fragment 1 -> Fragment 2 -> Fragment 3 if the previous id of Fragment 3 is >Fragment 2 then go back to it with arguments.

But I also will have a situation where this will happen:

Fragment 4 -> Fragment 3 here I want to be able to also check if the previous id/name of Fragment 3 is equal to Fragment 4 and if it is go back to that Fragment with arguments.

Basically Fragment 3 will have different routes out of it and I want to be able to determine which previous fragment it will go to next.

My problem is I am not able to get access to information from previous Fragments. To check if any of this is possible. I am new to using the Android Navigation Component so any help is appreciated.

If the question seems a little bit confusing please let me know so I can rewrite it if needed.

Thanks!

like image 924
OPWagg Avatar asked May 30 '19 16:05

OPWagg


1 Answers

You'd use 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

And to get the id of the previous destination use: previousBackStackEntry.destination.id but as it is nullable then use previousBackStackEntry?.destination?.id

Applying that in your scenario:

In Fragment 3:

val previousFragment = findNavController().previousBackStackEntry?.destination?.id

previousFragment?.let {
    when (previousFragment) {
        R.id.fragment_2_id ->
            // The previous fragment is Fragment 2

        R.id.fragment_4_id ->
            // The previous fragment is Fragment 4

        else ->
            // The previous fragment is neither Fragment 2 nor 4
    }
}
like image 94
Zain Avatar answered Sep 22 '22 04:09

Zain