FragmentTransaction add 和 replace 完全解析

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 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值