Home > front end >  Android Navigation - Popping the current fragment when navigating
Android Navigation - Popping the current fragment when navigating

Time:11-24

I have a fragment that can be dynamically navigated to from anywhere in my app, however, when the user leaves this fragment it shouldn't be added to the backstack.

E.g. if a user is at fragment A and navigates to this fragment (B) then to fragment C, when they click back they should arrive at fragment A not fragment B.


I have tried calling the following in fragment B:

findNavController().navigate(
   resId = R.id.C, 
   navOptions = NavOptions.Builder()
       .setPopUpTo(R.id.B, inclusive = true)
       .build()
)

however, this does not work. Additionally, I cannot call this from fragment B:

findNavController().navigate(
   resId = R.id.C, 
   navOptions = NavOptions.Builder()
       .setPopUpTo(R.id.A, inclusive = false) // this line is different
       .build()
)

as B does not know what its predecessor is.


Alternatively, I cannot call something like this in C on back navigation:

findNavController().popBackStack(R.id.A, inclusive = false)

or something like this in C on fragment creation:

findNavController().popBackStack()

as C does not necessarily know when its predecessor is either.


To make this even harder, I cannot call navigateBack() and then navigate() in fragment B for reasons internal to my app.

I believe this may be possible if I were to check the back stack and add some dynamic calls, however, this feels like a hacky solution.

Is there any neat way to do this?

CodePudding user response:

I have tried calling the following in fragment B:

findNavController().navigate(
   resId = R.id.C, 
   navOptions = NavOptions.Builder()
       .setPopUpTo(R.id.B, inclusive = true)
       .build()
)

This solution should normally work, there was an internal bug in my app preventing the navOptions from reaching the navigate() call.

  • Related