使用 FragmentTransaction 的時候,它提供了這樣兩個方法,一個 add , 一個 replace .
add 和 replace 影響的只是界面,而控制回退的,是事務。
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.
add 是把一個fragment添加到一個容器 container 里。
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.
replace 是先remove掉相同id的所有fragment,然后在add當前的這個fragment。
在大部分情況下,這兩個的表現基本相同。因為,一般,咱們會使用一個FrameLayout來當容器,而每個Fragment被add 或者 replace 到這個FrameLayout的時候,都是顯示在最上層的。所以你看到的界面都是一樣的。但是,使用add的情況下,這個FrameLayout其實有2層,多層肯定要比一層的來得浪費,所以還是推薦使用replace。當然有時候還是需要使用add的。比如要實現輪播圖的效果,每個輪播圖都是一個獨立的Fragment,而他的容器FrameLayout需要add多個Fragment,這樣他就可以根據提供的邏輯進行輪播了。
而至於返回鍵的時候,這個跟事務有關,跟使用add還是replace沒有任何關系。