2

I have several fragments that keep replacing each other (with the transactions added to the backstack). Depending on user actions at some point I need to clear all (or some) of the previous fragments and show only 1 new fragment.

To do this I currently do a popBackStack() to clear them first and then do a replace(), this works as expected. However sometimes there is a flash of the previous fragment before we see the new fragment. I think this is because I am popping the backstack first before showing the new fragment.

So I'm just wondering if there is a simple way to first display the new fragment and then clear the backstack of the previous transactions?

source.rar
  • 8,002
  • 10
  • 50
  • 82

1 Answers1

0

Edit: You are right, it is because you are removing from the back stack before adding the fragment.

If you dont need the new fragment on the back stack you can just add the new fragment first in a single transaction and pop the rest of the fragments from the back stack after the transaction. (or if you do need it, remove all fragments from the back stack except the newly added one)

Also if you just call replace(R.id.containter, new Fragment(), TAG) all fragments added to the container will be replaced with the new one. (you can then also clear the back stack manually)

Both of this solutions should remove the flash you see sometimes, since in your case you start removing fragments before adding a new and thus you can see the old ones removing themselves.

If the problem still occurs, you can try clearing your back stack after the newly fragment has been attached in to the activity and shown itself(but i dont think it will be necessary, i tried the above solutions where i call add fragment first and pop the whole backstack right after)

JanBo
  • 2,925
  • 3
  • 23
  • 32
  • how would one do this if you only want to pop the previous 1 (or 'n') fragment in some cases? When I popBackStack() after adding a new fragment the new fragment is never shown. – source.rar Feb 14 '15 at 12:48
  • It will take some work, but here is the solution you need to impement in order to achieve the effect. http://stackoverflow.com/questions/21665346/android-reorder-fragment-backstack/22125826#22125826 – JanBo Feb 14 '15 at 14:06
  • But before you try that, have you set custom animations on your fragment transactions? – JanBo Feb 14 '15 at 14:09
  • Yes I plan to do add animations, thats why am looking for the proper way to clear it first. :) – source.rar Feb 14 '15 at 14:18
  • Well i think the flash will go away it that case. If you say for ex. add a few fragments to back stack, and then popbackStack(null, INCLUSIVE) and call replace, you will see the last fragment leave and the new one enter. – JanBo Feb 14 '15 at 14:41