Remove all fragments from container

前端 未结 9 1580
死守一世寂寞
死守一世寂寞 2021-02-01 00:56

Is there a way to remove all fragments which already added the specific view with its view id?

For example I want to remove all fragments which is added R.id.fragmentcon

9条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-01 01:51

    Its very simple just loop through all the fragments and remove it

    for (Fragment fragment : getSupportFragmentManager().getFragments()) {
        getSupportFragmentManager().beginTransaction().remove(fragment).commit();
    }
    

    But in case of Navigation Drawer be sure to check it, if you try to remove it you will get error.

    for (Fragment fragment : getSupportFragmentManager().getFragments()) {
      if (fragment instanceof NavigationDrawerFragment) {
          continue;
      }
      else { 
          getSupportFragmentManager().beginTransaction().remove(fragment).commit();
      }
    }
    

    Last but very important be sure to check for null before doing any fragment transactions

    for (Fragment fragment : getSupportFragmentManager().getFragments()) {
        if (fragment instanceof NavigationDrawerFragment) {
            continue;
        }
        else if (fragment != null) {
            getSupportFragmentManager().beginTransaction().remove(fragment).commit();
        }
    }
    

提交回复
热议问题