fragment中有兩種常用的加載方式:
replace
-
hide
與shou
之前一直沒考慮過這個問題,今天突然想起來了替梨,就順便進(jìn)去看下源碼
replace
源碼中對replace
方法的說明是這樣的
/**
* Replace an existing fragment that was added to a container. This is
* essentially the same as calling {@link #remove(Fragment)} for all
* currently added fragments that were added with the same containerViewId
* and then {@link #add(int, Fragment, String)} with the same arguments
* given here.
*
* @param containerViewId Identifier of the container whose fragment(s) are
* to be replaced.
* @param fragment The new fragment to place in the container.
* @param tag Optional tag name for the fragment, to later retrieve the
* fragment with {@link FragmentManager#findFragmentByTag(String)
* FragmentManager.findFragmentByTag(String)}.
*
* @return Returns the same FragmentTransaction instance.
*/
public abstract FragmentTransaction replace(@IdRes int containerViewId, Fragment fragment,
@Nullable String tag);
其實就是add一個巩梢,然后remove一個,替換關(guān)系
show和hide
再來看show涯曲,顯示一個之前隱藏的fragment芽卿,這說明他并沒有被remove,而是被hide了抑淫,那么hide就不用看了绷落,肯定放到堆棧了,要show的時候始苇,直接拿出來就行砌烁,不會重新new一個
/**
* Shows a previously hidden fragment. This is only relevant for fragments whose
* views have been added to a container, as this will cause the view to
* be shown.
*
* @param fragment The fragment to be shown.
*
* @return Returns the same FragmentTransaction instance.
*/
public abstract FragmentTransaction show(Fragment fragment);
總結(jié)
那么綜合來說的話,如果單頁數(shù)據(jù)量較大的話催式,用show和hide還好一些函喉,畢竟二次加載起來要快很多,但是可能會產(chǎn)生內(nèi)存不足的情況荣月。replace雖然不用就干掉管呵,但是二次加載會慢一些,然而今天之所以要記錄一下,是因為我突然發(fā)現(xiàn)replace
還提供了一個api
/**
* Add this transaction to the back stack. This means that the transaction
* will be remembered after it is committed, and will reverse its operation
* when later popped off the stack.
*
* @param name An optional name for this back stack state, or null.
*/
public abstract FragmentTransaction addToBackStack(@Nullable String name);
加到堆棧哺窄,要用的時候直接取出來捐下,那么如果replace加上這個就和show與hide有的一拼了。
這樣封裝一下fragment切換器效果就好多了
public void fragmentReplace(int target, Fragment toFragment, boolean backStack) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
String toClassName = toFragment.getClass().getSimpleName();
if (manager.findFragmentByTag(toClassName) == null) {
transaction.replace(target, toFragment, toClassName);
if (backStack) {
transaction.addToBackStack(toClassName);
}
transaction.commit();
}
}
如果要放到緩存直接給backStack傳true即可堂氯。