pop specific fragment from stack and remove others

2019-03-19 10:33发布

问题:

how I can pop specific fragment from stack and remove others from a fragment? for example these are my fragments and I'm in E right know.

A-> B -> C -> D ->E

wanna back from E to B and Clear C and D. How I can do this?

回答1:

You can add a tag to each fragment while adding them to the backstack and then popfragment from backstack till the fragment with the tag you want is not reached.

FragmentManager fm = getFragmentManager();

for (int i = fm.getBackStackEntryCount() - 1; i > 0; i--) {
    if (!fm.getBackStackEntryAt(i).getName().equalsIgnoreCase(tagname)) {
        fm.popBackStack();
    }
    else
    {
     break;
    }
}


回答2:

Use the can call the function below while you are in Fragment E:

getFragmentManager().popBackStack("tag", 0);

Here the tag is string passed as tag while adding fragment B to backstack.



回答3:

Use following code for pop back stack entry:

 FragmentManager fm = getSupportFragmentManager();

    if (fm.getBackStackEntryCount() > 0) {

        fm.popBackStack();

    }else {
        super.onBackPressed();
    }