如果你已经使用过fragment,我先提出几个问题。
1、按返回键的时候,如果当前的fragment是加入到栈的(其实这个说法不是很准确,因为真正加入栈的是操作fragment的事务),那么这个fragment会被remove掉,而如果没有加入栈,那么回退按键对这个fragment一点反应也没有?
2、加入到栈的fragment在被remove的时候,其生命周期走到onDestroyView而没有走到onDestroy,而没有加入栈的话,会走到onDestroy?
你可以先代码验证如上问题,然后自己寻找答案
下面是我读源码时候的理解;
1、按返回键,本质上是调用popBackStack(….)方法,最终会从事务栈中取出最近的一个事务,然后执行操作,如果当初add这个fragment的时候没有加入栈,当然从中找不到事务,也不会对当前fragment有影响。
部分代码如下:
boolean popBackStackState(Handler handler, String name, int id, int flags) {
if (mBackStack == null) {
return false;
}
if (name == null && id < 0 && (flags&POP_BACK_STACK_INCLUSIVE) == 0) {
int last = mBackStack.size()-1;
if (last < 0) {
return false;
}
//取出最近的事务,BackStackRecord 其实对应的就是 FragmentTransaction
final BackStackRecord bss = mBackStack.remove(last);
SparseArray<Fragment> firstOutFragments = new SparseArray<Fragment>();
SparseArray<Fragment> lastInFragments = new SparseArray<Fragment>();
if (mCurState >= Fragment.CREATED) {
bss.calculateBackFragments(firstOutFragments, lastInFragments);
}
bss.popFromBackStack(true, null, firstOutFragments, lastInFragments);
reportBackStackChanged();
}
2、加不加入到栈,会什么在remove操作时候,会影响到onDestroy生命周期,这个我们从源码看下,
2.1 先看removeFragment,看我的注释
public void removeFragment(Fragment fragment, int transition, int transitionStyle) {
if (DEBUG) Log.v(TAG, "remove: " + fragment + " nesting=" + fragment.mBackStackNesting);
//此处关键,如果加入栈,inactive 为false,否则为true
final boolean inactive = !fragment.isInBackStack();
if (!fragment.mDetached || inactive) {
if (mAdded != null) {
mAdded.remove(fragment);
}
if (fragment.mHasMenu && fragment.mMenuVisible) {
mNeedMenuInvalidate = true;
}
fragment.mAdded = false;
fragment.mRemoving = true;
//走到这个方法
moveToState(fragment, inactive ? Fragment.INITIALIZING : Fragment.CREATED,
transition, transitionStyle, false);
}
}
moveToState 方法,从上面传进来的newState,如果加入栈,其值为Fragment.CREATED,否则为Fragment.INITIALIZING