简体   繁体   中英

How to dismiss fragment in back stack

I have 3 fragments A, B, C and I replace from A to B and then C but I need to on backpresed go from C to A. I mean not include fragment B in history stack and here is mode code

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(container, fragment);
transaction.addToBackStack(null);
transaction.commit();

Fragment B更改为Fragment C时,请勿将FragmentTanscation添加到BackStack。因此在backPress上,您将直接获得Fragment A。

When you replace fragment A with fragment B, transaction.addToBackStack(null) should be added to add A to the stack

But when replacing B with C, don't write addToBackStack so B won't be added and you'll be able to navigate back to A when pressing the back button from C

If your code is generic for all your fragments you'll have to write some code to exclude one fragment from being added to the backstack.

Should look something like this

private void addFragments() {
    Fragment a = new A();
    Fragment b = new B();
    Fragment c = new C();

    doFragmentTransaction(a, true);
    doFragmentTransaction(b, false);
    doFragmentTransaction(c, true);
}

private void doFragmentTransaction(Fragment fragment, boolean addToBackstack) {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(container, fragment);

    if (addToBackstack)
        transaction.addToBackStack(null);

    transaction.commit();
}

Use this Code for getting Fragmnet from C to A in onBackpressed method :

FragmentManager fm = getActivity().getSupportFragmentManager();
for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {    

FragmentManager.popBackStack(String name, FragmentManager.POP_BACK_STACK_INCLUSIVE)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM