博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
FragmentTransaction add 和 replace 完全解析
阅读量:6953 次
发布时间:2019-06-27

本文共 1488 字,大约阅读时间需要 4 分钟。

hot3.png

#FragmentTransaction FragmentTransaction是fragment的管理工具,可进行fragment的添加,移除,替换,以及执行其他操作。可以通过FragmentManager获取其实例。

fragmentManager.beginTransaction();

###add()

add() 是把一个fragment添加到一个容器 container 里。

Add a fragment to the activity state. This fragment may optionally also have its view (if Fragment.onCreateView returns non-null) into a container view of the activity.

Parameters containerViewId Optional identifier of the container this fragment is to be placed in. If 0, it will not be placed in a container. fragment The fragment to be added. This fragment must not already be added to the activity. tag Optional tag name for the fragment, to later retrieve the fragment with FragmentManager.findFragmentByTag(String). Returns Returns the same FragmentTransaction instance.

###replace() replace 是先remove掉相同id的所有fragment,然后在add当前的这个fragment。

public abstract FragmentTransaction replace (int containerViewId, Fragment fragment, String tag)

Replace an existing fragment that was added to a container. This is essentially the same as calling remove(Fragment) for all currently added fragments that were added with the same containerViewId and then add(int, Fragment, String) with the same arguments given here.

两个方法都可以实现显示一个新的fragment的效果,但是 add()只是单纯的新增一个并且会重新执行新fragment里面的初始化方法,比如注册通知事件,这样会造成重复注册出错。 还有replace()会先remove()相同id的所有fragment,如果没有相同id的所有fragment则只能用add(),否则会出现错误,如

java.lang.IllegalArgumentException:No view found for id for fragment

转载于:https://my.oschina.net/u/865535/blog/498400

你可能感兴趣的文章
UVA - 10574 Counting Rectangles
查看>>
HDU3336-Count the string(KMP)
查看>>
常用API接口签名验证参考
查看>>
Linux中find常见用法示例
查看>>
bootstrap 模态框动态加载数据
查看>>
初始化构造函数中定义的实体集合,方便嵌套类型的遍历
查看>>
深入理解css3中nth-child和 nth-of-type的区别
查看>>
MySQL慢查询Explain Plan分析
查看>>
MyBatis原理分析之三:初始化(配置文件读取和解析)
查看>>
180321
查看>>
Spark2.1.0之源码分析——事件总线
查看>>
Htmlparser专题
查看>>
大数据开发实战:数据平台大图和离线数据平台整体架构
查看>>
Spring MVC 3 深入总结
查看>>
Android自定义控件View(一)
查看>>
C/C++中的getline函数总结:
查看>>
【转】雪崩光电二极管(APD)偏置电源及其电流监测
查看>>
关于CAShapeLayer的一些实用案例和技巧
查看>>
Android中Service 使用详解(LocalService + RemoteService)
查看>>
使用scrapy抓取Youtube播放列表信息
查看>>