Remove all fragments from container

2020-02-17 10:02发布

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.fragmentcontainer view.

8条回答
家丑人穷心不美
2楼-- · 2020-02-17 10:29

It is indeed very simple.

private static void removeAllFragments(FragmentManager fragmentManager) {
    while (fragmentManager.getBackStackEntryCount() > 0) {
        fragmentManager.popBackStackImmediate();
    }
}
查看更多
Summer. ? 凉城
3楼-- · 2020-02-17 10:32

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();
    }
}
查看更多
登录 后发表回答