Forum Xamarin.Android

How do I remove all fragments in the backstack?

bananaprinterbananaprinter USMember ✭✭
edited August 2020 in Xamarin.Android

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

Appreciate any help!

Best Answer


  • bananaprinterbananaprinter USMember ✭✭

    I am surprised it works.

    Thank you

Sign In or Register to comment.