Remove fragments from backstack android?

689 views Asked by At

I have total of 7 fragments

Frag1 -> Frag2 -> Frag3 -> Frag4 -> Frag5 -> Frag6 -> Frag7 

The user navigates from Frag1 -> Frag7 So, when the user is on Frag7 and presses the back button Frag1 should be visible.

This is fragment transaction code

    public void displayView(Fragment fragment, Bundle data) {
    if (fragment != null) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();
        if (data != null) {
            if (fragment.getArguments() != null) {
                fragment.getArguments().putAll(data);
            } else {
                fragment.setArguments(data);
            }
        }
        if (!fragment.isAdded()) {
            ft.replace(R.id.frame, fragment);
            ft.addToBackStack(null);
        }
        ft.commit();
    } else {
        Logger.e("MainActivity", "Error in creating fragment");
    }
}

I called getActivity().getSupportFragmentManager().popBackStack(); 5 times before moving to Frag7, but I always get this as backstack

Frag7 -> Frag6 -> Frag1

I am unable to remove the current fragment (Frag6) from where the user navigates.

2

There are 2 answers

0
Manish On

pls try below logic when u r going from Frag1 -> Frag2 pls use ft.addToBackStack(null);

and after that when u r navigating from

Frag2 -> Frag3 -> Frag4 -> Frag5 -> Frag6 -> Frag7 

u did not need to add to backstack means do not call add to backStack();

0
Pranav Darji On

You can try below code yourfragmentName is the fragment where you want to redirect

   if (getFragmentManager().getBackStackEntryCount() > 0) {
         getFragmentManager().popBackStack(yourfragmentName.class.getSimpleName(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
}