Skip to content Skip to sidebar Skip to footer

Android: Not Getting How Popbackstackimmediate () Behaves

I have 3 Fragments and the flow is like Fragment 1 --> Fragment 2 (adding it to back stack)--> Fragment 3 --> Fragment 1 As I want to go to Fragment 1 from Fragment 3 a

Solution 1:

I looked at your code in the other question and I think I understand what the problem is.

So your first action is that you create Fragment 1 and put it in a container. I don't see code for that but no matter; if the container is empty then add and replace act the same way. So now your Fragment 1 is in the container.

You haven't called addToBackStack here so the FragmentManager doesn't know how to undo this operation. That's fine, it's the first operation and doesn't need to be undone.

Next you create Fragment 2 and do a replace transaction. Fragment 1 is replaced with Fragment 2. This is pushed to the back stack so the FragmentManagerdoes know how to undo this transaction.

Next you create Fragment 3 and do a replace transaction. Fragment 2 is replaced with Fragment 3. You don't push this operation to the back stack. Uh oh.

Now when you say popBackStack (deferred or immediate) the FragmentManager goes to undo the operation to replace Fragment 2 with Fragment 1 but Fragment 2 isn't in the container anymore. So (from what I understand) the FragmentManager will put Fragment 1 back in the container but leave Fragment 3 there. It doesn't know what to do with Fragment 3.


Here is how I handle those kinds of scenarios: Say I have Fragment 1, then navigate to Fragment 2. To navigate to Fragment 3 when I intend the back button to go to Fragment 1, I do this:

  1. Pop the back stack (immediate, now Fragment 1 is back in the container) then
  2. Replace Fragment 1 with Fragment 3 and push that operation to the back stack.

Now when I press the back button, the FragmentManager knows how to undo my operation and puts Fragment 1 back where Fragment 3 was. This means that I don't have to perform any fragment transactions to handle this back navigation, the FragmentManager handles it all for me.

Post a Comment for "Android: Not Getting How Popbackstackimmediate () Behaves"