I have a problem about removing a specific fragment from back stack.My scenario is like this.Fragment-1 is replaced with Fragment-2 and then Fragment-2 is replaced with Fragment-3.
Calling order; Fragment-1-->Fragment-2-->Fragment-3.
When Fragment-3 is on the screen and then back button is clicked, i want to go
Fragment-1.That means i want to delete Fragment-2 from back stack.
How to do this ?
If you are adding/launching all three fragments in the same activity, instead of the
add()
method of FragmentTransaction for showing Fragment3, use thereplace()
method of FragmentTransaction (replace Fragment2 with Fragment3). Thereplace
method removes the current fragment from backstack before adding the new fragment. If you are launching Fragment3 from a different activity, and thus you can't/don't want to usereplace()
, remove Fragment2 from backstack before starting the new activity (which adds fragment3):I had a very similar scenario to yours, my solution was just checking the amount of backStack transactions that I had.
If the transactions where more than 0 then I would simply pop it right away so it would skip it when pressing back.
This would successfully:
A -> B (back pressed) -> back to A
A -> B -> C (back pressed) -> back to A
The only downside that I see is that there is a quick flash where fragment A is displayed before going to fragment C.
You add to the back state from the
FragmentTransaction
and remove from the backstack usingFragmentManager
pop methods:OR
Simply you can skip the fragment from adding into the fragment stack so when you come back from
Fragment-3
it will come back toFragment-1
Updated :
To disable the animation, you need to override the
onCreateAnimation
method...Code for Fragment A -> Fragment B:
Add Fragment A in BackStack of Fragments
Code for Fragment B -> Fragment C:
Do not Add Fragment B in BackStack of Fragments
It will works in this way: A -> B -> C and while returning C-> A as you excepted.
Hope it will help you.
In the backstack you don't have
Fragment
s, butFragmentTransaction
s. When youpopBackStack()
the transaction is applied again, but backward. This means that (assuming youaddToBackStackTrace(null)
every time) in your backstack you haveIf you don't add the second transaction to the backstack the result is that your backstack is just
and so pressing the back button will cause the execution of
2->1
, which leads to an error due to the fragment 2 not being there (you are on fragment 3).The easiest solution is to pop the backstack before going from 2 to 3
What I'm doing here is these: from fragment 2 I go back to fragment 1 and then straight to fragment 3. This way the back button will bring me again from 3 to 1.