美文网首页
fragment replace

fragment replace

作者: sys_out | 来源:发表于2019-08-09 17:13 被阅读0次

关于replace方法的一个特点记录下。
看到源码注释我们知道replace其实本质上等同于 remove + add。

 getSupportFragmentManager().beginTransaction().replace(R.id.fl, customFragment, "tag" + tag)
                    .addToBackStack(getClass().getName()).commit();

等同于

getSupportFragmentManager().beginTransaction().remove(getSupportFragmentManager().findFragmentByTag("tag" + (tag - 1)))
                    .add(R.id.fl, customFragment, "tag" + tag)
                    .addToBackStack(getClass().getName()).commit();

特点就是当replace之后,我觉得之前的fragment应该被删除调了。但是,通过findFragmentByTag还是可以获取到改fragment对象。说明它还存在内存当中。
不过当点击back键,回退之后,被回退的fragment对象就变成null了。

至于为什么能力不够,源码较复杂。猜测这里这两个集合,remove的时候被加到了mActive集合中,add的被加到了mAdded中。栈回退的时候可能就把mActive中的也删除调了

final ArrayList<Fragment> mAdded = new ArrayList<>();
final HashMap<String, Fragment> mActive = new HashMap<>();

相关文章

网友评论

      本文标题:fragment replace

      本文链接:https://www.haomeiwen.com/subject/egihjctx.html