How to clear Fragment backstack in android

前端 未结 6 863
别跟我提以往
别跟我提以往 2020-12-05 01:37

hi how to clear fragment back stack am using below logic it\'s not working...

for(int i = 0; i < mFragmentManager.getBackStackEntryCount(); ++i) {                 


        
相关标签:
6条回答
  • 2020-12-05 02:06

    Try this

    mFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); 
    
    0 讨论(0)
  • 2020-12-05 02:06

    Answer above is almost correct, but you need a guard around the fragment back list as it can be empty:

    private void clearBackStack() {
        FragmentManager manager = getSupportFragmentManager();
        if (manager.getBackStackEntryCount() > 0) {
            FragmentManager.BackStackEntry first = manager.getBackStackEntryAt(0);
             manager.popBackStack(first.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
        }
    }
    
    0 讨论(0)
  • 2020-12-05 02:09

    This is a bit late but I just had this problem myself. You can do:

    FragmentManager manager = getFragmentManager();
    FragmentManager.BackStackEntry first = manager.getBackStackEntryAt(0);
    manager.popBackStack(first.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
    

    Pretty self explanatory; you just get the first entry, get its id, and then pop everything up to and including the entry with that id.

    0 讨论(0)
  • 2020-12-05 02:17

    one way is to tag the backstack and when you want to clear it

    mFragmentManager.popBackStack("myfancyname", FragmentManager.POP_BACK_STACK_INCLUSIVE);
    

    where the "myfancyname" should match the string you used with addToBackStack. E.g.

    Fragment fancyFragment = new FancyFragment();     
    fragmentTransaction.replace(R.id.content_container, fancyFragment, "myfragmentag");
    fragmentTransaction.addToBackStack("myfancyname");
    

    the backstack's name and the fragment's tag name can be the same but there are no constrains on this regard

    From the documentation

    If set, and the name or ID of a back stack entry has been supplied, then all matching entries will be consumed until one that doesn't match is found or the bottom of the stack is reached. Otherwise, all entries up to but not including that entry will be removed.

    if you don't want to use a name for your backstack you can pass use a first parameter

     mFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
    
    0 讨论(0)
  • 2020-12-05 02:23

    The best option I ever seen is here.

                int count = getSupportFragmentManager().getBackStackEntryCount();
                if (count > 0) {
                    getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                }
    
    0 讨论(0)
  • 2020-12-05 02:27
    while (getSupportFragmentManager().getBackStackEntryCount() > 0){
        getSupportFragmentManager().popBackStackImmediate();
    }
    
    0 讨论(0)
提交回复
热议问题