5

What I am exactly looking for is that wether my fragment is already in the back stack or not.

For example, I navigate to Fragment A to Fragment B. Later, I navigate to Fragment B to Fragment C. Now, I want to check in the Fragment C that is there Fragment A available in the back stack. If yes, I want to pop out all the fragments up to Fragment A else I want to add new Fragment A.

Please make sure I want to check availability of Fragment A in Fragment C.

Is there any luck?

Thanks in advance.

Harsh Patel
  • 657
  • 11
  • 26
  • I don't think Navigation AAC was designed for that usecase, however you could potentially use `fragmentManager.getFragments()` and iterate through the currently added fragments. – EpicPandaForce Aug 12 '19 at 14:16

1 Answers1

5

What I am exactly looking for is that wether my fragment is already in the back stack or not.

There is a way to do that using NavController.

try {
    val back:NavBackStackEntry = controller.getBackStackEntry(R.id.nav_a)
    Log.d("in_back_stack", back.destination.label.toString())
} catch (ex: IllegalArgumentException){
    Log.d("in_back_stack","no_entry")
}

Using NavController.getBackStackEntry(...) & destinationId you can easily know whether a fragment is already in the back stack or not. But be careful using this method. As the method will throw an IllegalArgumentException if the destinationId is not found in the back stack.

Please make sure I want to check availability of Fragment A in Fragment C.

You can check from anywhere. All you need is reference of the NavController.

zoha131
  • 1,758
  • 2
  • 16
  • 18