从容器中取出所有碎片 [英] Remove all fragments from container

查看:42
本文介绍了从容器中取出所有碎片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以删除所有已经添加了特定视图及其视图ID的片段?

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

例如,我要删除添加到R.id.fragmentcontainer视图中的所有片段.

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

推荐答案

非常简单,只需遍历所有片段并将其删除

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();
    }
}

这篇关于从容器中取出所有碎片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆