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 

你可能感兴趣的:(android开发)