Reputation: 1674
I've been working with fragments for a while now, but I regularly encounter a problem that just annoys me. Fragments remain drawn over each other some times. Now, I managed to isolate one use case for this, and it goes like this:
Add Fragment A
(also use addToBackStack with a name "backstack_state"
)
Replace Fragment A
with Fragment B
(use addToBackStack
)
Replace Fragment B
with Fragment C
WITHOUT using addToBackStack
at a given point use popBackStack("backstack_state", 0)
and here comes the issue:
The backstack is popped until Fragment A
but Fragment C
is overlaid with Fragment A
, both are visible at the same time. Is this normal behavior or is it me who makes a mistake?
Here's a remark also: all the fragments have transparent background.
Thanks!
Upvotes: 2
Views: 637
Reputation: 71
This happens because the top fragment (in this case Fragment C) is not removed. You have to remove it first inside a fragment transaction. Try this:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment topFragment = fragmentManager.findFragmentById(R.id.fragment_container);
if (topFragment != null) {
fragmentTransaction.remove(topFragment);
}
fragmentTransaction.commit();
fragmentManager.popBackStack("backstack_state", 0);
Upvotes: 1