FragmentTransaction add 和 replace 徹底解析

#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
相關文章
相關標籤/搜索