Hello everyone. In my application I have a MainActivity with multiple fragments, the problem is I want to clear the backstack after replacing a specific fragment. This is because when there are multiple fragments in the backstack the application starts to perform poorly.
Explanation: MainFragment -> Fragment A -> Fragment B (this is added to backstack) -> Fragment C -> MainFragment (clear backstack ).
The problem: After Fragment C is replaced with MainFragment, if the user presses the back button all the other fragments show up.
I have tried multiple approaches such as a while loop with a .PopBackStackImmediate() for every fragment in backstack but the problem persists.
This is my function for replacing fragments:
public void ReplaceFragment(Fragment fragment) { var fragmentManager = this.ParentFragmentManager.BeginTransaction(); fragmentManager.Replace(Resource.Id.frameLayout1, fragment); fragmentManager.AddToBackStack(null); // comment this line to not add fragment to backstack fragmentManager.Commit(); }
Appreciate any help!
The FragmentManager class provides the PopBackStack which could help to clear the back stack. Try getting the count of back stack, then traverse this collection to remove the clear the stack.
Check the code:
var count = SupportFragmentManager.BackStackEntryCount; for (int i = 0; i < count; i++) { SupportFragmentManager.PopBackStack(); }
Similar issue:
https://stackoverflow.com/questions/6186433/clear-back-stack-using-fragments
Answers
The FragmentManager class provides the PopBackStack which could help to clear the back stack. Try getting the count of back stack, then traverse this collection to remove the clear the stack.
Check the code:
Similar issue:
https://stackoverflow.com/questions/6186433/clear-back-stack-using-fragments
I am surprised it works.
Thank you