#FragmentTransaction FragmentTransaction是fragment的管理工具,可进行fragment的添加,移除,替换,以及执行其余操做。能够经过FragmentManager获取其实例。java
fragmentManager.beginTransaction();
###add()ide
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.this
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.code
###replace() replace 是先remove掉相同id的全部fragment,而后在add当前的这个fragment。事件
public abstract FragmentTransaction replace (int containerViewId, Fragment fragment, String tag)rem
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.it
两个方法均可以实现显示一个新的fragment的效果,可是 add()只是单纯的新增一个而且会从新执行新fragment里面的初始化方法,好比注册通知事件,这样会形成重复注册出错。 还有replace()会先remove()相同id的全部fragment,若是没有相同id的全部fragment则只能用add(),不然会出现错误,如io
java.lang.IllegalArgumentException:No view found for id for fragment