fragment中的replace和hide与shou方法的区别
2017-07-27 本文已影响138人
世外大帝
fragment中有两种常用的加载方式:
replace
-
hide
与shou
之前一直没考虑过这个问题,今天突然想起来了,就顺便进去看下源码
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一个,替换关系
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);
总结
那么综合来说的话,如果单页数据量较大的话,用show和hide还好一些,毕竟二次加载起来要快很多,但是可能会产生内存不足的情况。replace虽然不用就干掉,但是二次加载会慢一些,然而今天之所以要记录一下,是因为我突然发现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即可。