fragment的状态保存&恢复过程分析

作者: tmp_zhao | 来源:发表于2016-05-02 19:09 被阅读2577次

缘起

之前已经做了关于fragment源码的分析,但貌似把fragment关于保存、恢复的内容给忽略了,再加上上周5在开发一个功能时遇到了一个奇怪的现象,当时真是怎么也想不明白,而且单步调试发现状态也都是对的,但是界面渲染完就又不对了,呃。。。

这里先解释下我那个功能的大概样子:fragment包括一个可以滚动的LinearLayout,可以动态添加多个item view,item view是包括了一个checkbox,多个textview这样的东西,同时只有一个item view可以被选中。奇怪的现象是:fragment第2次show出来的时候,默认应该选中的项没有被选中,第1次就完全没这个问题,这里我重用了同一个fragment的实例。

此现象的原因分析

没办法这个问题的原因不查出来,真是吃饭都走神。老话讲,大胆假设,小心求证。既然checkbox的状态不对,那么我立马感觉只能是checkbox的setChecked方法被我还不知道的地方调用了,于是我将系统的checkbox换成了自己继承的MyCheckbox,然后override了setChecked方法,并在那里加了些log,再次run了一遍,果然不出所料,输出了一堆日志。那就证明了我的猜想,确实是不知道什么地方再次调用了setChecked方法,覆盖了我自己在onCreateView里面关于checkbox的设置。接下来就很简单了,我在重载的方法那里挂了个断点,很快就知道了调用栈,如下:


在本文的最后,我们再来详细分析为什么会发生这个行为。

fragment保存、恢复过程

View树的状态保存、恢复一文中我们已经分析了绝大部分的内容,那里忽略了关于fragment的代码,我们在这里着重讲解下,来回顾下Activity.onSaveInstanceState方法:

protected void onSaveInstanceState(Bundle outState) {
        outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());
        // view树的状态保存完之后,处理fragment相关的
        Parcelable p = mFragments.saveAllState();
        if (p != null) {
            outState.putParcelable(FRAGMENTS_TAG, p);
        }
        getApplication().dispatchActivitySaveInstanceState(this, outState);
    }

protected void onCreate(@Nullable Bundle savedInstanceState) {
        if (DEBUG_LIFECYCLE) Slog.v(TAG, "onCreate " + this + ": " + savedInstanceState);
        if (mLastNonConfigurationInstances != null) {
            mFragments.restoreLoaderNonConfig(mLastNonConfigurationInstances.loaders);
        }
        if (mActivityInfo.parentActivityName != null) {
            if (mActionBar == null) {
                mEnableDefaultActionBarUp = true;
            } else {
                mActionBar.setDefaultDisplayHomeAsUpEnabled(true);
            }
        }
        if (savedInstanceState != null) {
            Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
            // 恢复fragment相关的状态
            mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
                    ? mLastNonConfigurationInstances.fragments : null);
        }
        mFragments.dispatchCreate();
        getApplication().dispatchActivityCreated(this, savedInstanceState);
        if (mVoiceInteractor != null) {
            mVoiceInteractor.attachActivity(this);
        }
        mCalled = true;
    }

从上面的源码可以看出,fragment的状态保存、恢复是根据外面的act来进行的,也就是说它的调用时机是和act一致的。
mFragments.saveAllState();
这行代码最终会调到FragmentManagerImpl.saveAllState方法,代码如下:

Parcelable saveAllState() {
        // Make sure all pending operations have now been executed to get
        // our state update-to-date.
        execPendingActions();

        mStateSaved = true;

        if (mActive == null || mActive.size() <= 0) {
            return null;
        }
        
        // First collect all active fragments.
        int N = mActive.size();
        FragmentState[] active = new FragmentState[N];
        boolean haveFragments = false;
        for (int i=0; i<N; i++) {
            Fragment f = mActive.get(i);
            if (f != null) {
                if (f.mIndex < 0) {
                    throwException(new IllegalStateException(
                            "Failure saving state: active " + f
                            + " has cleared index: " + f.mIndex));
                }

                haveFragments = true;

                FragmentState fs = new FragmentState(f);
                active[i] = fs;
                
                if (f.mState > Fragment.INITIALIZING && fs.mSavedFragmentState == null) {
                    fs.mSavedFragmentState = saveFragmentBasicState(f);

                    if (f.mTarget != null) {
                        if (f.mTarget.mIndex < 0) {
                            throwException(new IllegalStateException(
                                    "Failure saving state: " + f
                                    + " has target not in fragment manager: " + f.mTarget));
                        }
                        if (fs.mSavedFragmentState == null) {
                            fs.mSavedFragmentState = new Bundle();
                        }
                        putFragment(fs.mSavedFragmentState,
                                FragmentManagerImpl.TARGET_STATE_TAG, f.mTarget);
                        if (f.mTargetRequestCode != 0) {
                            fs.mSavedFragmentState.putInt(
                                    FragmentManagerImpl.TARGET_REQUEST_CODE_STATE_TAG,
                                    f.mTargetRequestCode);
                        }
                    }

                } else {
                    fs.mSavedFragmentState = f.mSavedFragmentState;
                }
                
                if (DEBUG) Log.v(TAG, "Saved state of " + f + ": "
                        + fs.mSavedFragmentState);
            }
        }
        
        if (!haveFragments) {
            if (DEBUG) Log.v(TAG, "saveAllState: no fragments!");
            return null;
        }
        
        int[] added = null;
        BackStackState[] backStack = null;
        
        // Build list of currently added fragments.
        if (mAdded != null) {
            N = mAdded.size();
            if (N > 0) {
                added = new int[N];
                for (int i=0; i<N; i++) {
                    added[i] = mAdded.get(i).mIndex;
                    if (added[i] < 0) {
                        throwException(new IllegalStateException(
                                "Failure saving state: active " + mAdded.get(i)
                                + " has cleared index: " + added[i]));
                    }
                    if (DEBUG) Log.v(TAG, "saveAllState: adding fragment #" + i
                            + ": " + mAdded.get(i));
                }
            }
        }
        
        // Now save back stack.
        if (mBackStack != null) {
            N = mBackStack.size();
            if (N > 0) {
                backStack = new BackStackState[N];
                for (int i=0; i<N; i++) {
                    backStack[i] = new BackStackState(this, mBackStack.get(i));
                    if (DEBUG) Log.v(TAG, "saveAllState: adding back stack #" + i
                            + ": " + mBackStack.get(i));
                }
            }
        }
        
        FragmentManagerState fms = new FragmentManagerState();
        fms.mActive = active;
        fms.mAdded = added;
        fms.mBackStack = backStack;
        return fms;
    }

从上面的代码我们可以看出,重点是对mActive的fragment的状态保存,调用的是以下方法:

Bundle saveFragmentBasicState(Fragment f) {
        Bundle result = null;

        if (mStateBundle == null) {
            mStateBundle = new Bundle();
        }
        // 回调callback函数,保存fragment的状态
        f.performSaveInstanceState(mStateBundle);
        if (!mStateBundle.isEmpty()) {
            // 确实有保存的东西则设置result
            result = mStateBundle;
            mStateBundle = null;
        }
        // 保存fragment view树的状态
        if (f.mView != null) {
            saveFragmentViewState(f);
        }
        if (f.mSavedViewState != null) {
            if (result == null) {
                result = new Bundle();
            }
            // 将view树的状态作为一个key、value放到result中
            result.putSparseParcelableArray(
                    FragmentManagerImpl.VIEW_STATE_TAG, f.mSavedViewState);
        }
        if (!f.mUserVisibleHint) {
            if (result == null) {
                result = new Bundle();
            }
            // Only add this if it's not the default value
            result.putBoolean(FragmentManagerImpl.USER_VISIBLE_HINT_TAG, f.mUserVisibleHint);
        }

        return result; // 返回最终的result作为fragment保存的状态
    }

void saveFragmentViewState(Fragment f) {
        if (f.mView == null) {
            return;
        }
        if (mStateArray == null) {
            mStateArray = new SparseArray<Parcelable>();
        } else {
            mStateArray.clear();
        }
        f.mView.saveHierarchyState(mStateArray);
        if (mStateArray.size() > 0) {
            f.mSavedViewState = mStateArray;
            mStateArray = null;
        }
    }

在继续分析之前,我们先来说下源码里的这2个字段之间的关系:



从上面的源码中我们可以看到mSavedViewState是作为fragment状态mSavedFragmentState的一个key/value对存在的,即只是fragment状态的一部分。

文章开头现象的原因分析

这里的重点还是fragment源码分析那篇文章中最后提到的FragmentManagerImpl的void moveToState(Fragment f, int newState, int transit, int transitionStyle, boolean keepActive)方法,这里我们截取关键的片段分析:

  1. 当fragment的状态在向前move的时候,即变大到resume状态的过程中,会经历这样的代码:

    f.restoreViewState的源码如下:
final void restoreViewState(Bundle savedInstanceState) {
        // 第一次show的时候,这个字段为null,所以不会触发
        // restoreHierarchyState方法
        if (mSavedViewState != null) {
            mView.restoreHierarchyState(mSavedViewState);
            mSavedViewState = null;
        }
        mCalled = false;
        onViewStateRestored(savedInstanceState);
        if (!mCalled) {
            throw new SuperNotCalledException("Fragment " + this
                    + " did not call through to super.onViewStateRestored()");
        }
    }

同时从源码我们也可以看出,此方法的调用时机是位于onActivityCreate之后,onStart之前,但都在onCreateView之后,所以如果mView.restoreHierarchyState起作用的话,那么我们在onCreateView里面的设置自然会被冲掉。

  1. 当fragment的状态在向后move的时候,即变小到INITIALIZING的过程中,会经历这样的代码:

saveFragmentViewState(f)方法会在onStop之后,onDestroyView之前被调用,这个方法我们前面介绍过,经过这个方法之后,f.mSavedViewState会被设置为有效值。所以在我们前面的例子里,当下次重用同一个实例时,由于f.mSavedViewState有值(即使fragment执行了onDestroyView之类的callback,调用了其initState方法,但mSavedViewState并不会被重置),所以就发生了前面截图里的调用栈了,即mView.restoreHierarchyState被调用了。而我们知道checkbox关于状态恢复的实现正好就是调用setChecked方法(在我们的案例里有多个checkbox,但只有1个是选中了,后面的所有都是没选中的,再加上是从同一个layout文件中inflate出来的,大家都有相同的id,在保存的过程中后面的checkbox状态就覆盖了前面选中了的checkbox状态),至此为止,真相大白,一切都解释通了。

总结

  1. fragment的状态保存、恢复和f.mView的状态保存、恢复发生的时机不一样,这两者不能等同;

  2. fragment的状态保存总体上是跟随外部的act的状态保存,当fragment保存状态时会触发f.mView的保存;fragment状态的恢复大体上是重建其mActive、mAdded、mBackStack这3个字段,时机是在外部act.onCreate里触发的;

  3. f.mView会在onDestroyView之前自动保存view树状态,并且在(同一个实例)onActivityCreate之后、onStart之前自动恢复之前保存的状态;

  4. 尽量别重用fragment实例,fragment最好不要有自己的字段,需要的参数可以通过setArguments(Bundle args)这样的方法传递进去;

  5. 如果遇上会产生相同view id的布局时,要特别关注下状态保存、恢复这方面,看看是否正常work,多实际测试;

相关文章

网友评论

  • 微小的沙土:楼主想问你个问题:我在页面消失时候有调用putFragment保存了Bundle,但是在恢复fragment时候getFragment时候有Bundle,但是mActive为Null,所以就崩了。。。咋回事?
  • AItsuki:简单来说,fragment中用到的view的状态是由fragment自身的实例保存的,并且在ondestroyview之前一定会保存。
    而fragment中除了view的其他状态,则是由phonewindow保存。

    另外,activity中用到的view则是由phonewindow保存的。

    我这么说对吗,view的状态保存,在activity和fragment中是稍微有区别的,保存他们状态的地方不一样,一个保存在phonewindow,一个保存在fragment.
    AItsuki:@tmp_zhao 嗯嗯 我知道这个意思:smile: 你的博文正好解决了我疑惑的问题
    tmp_zhao:怎么说呢?PhoneWindow只是作为上层起点,起个触发的作用;要说真正存储的地方,那是SparseArray<Parcelable>这样的对象;
  • AItsuki:不给你两块钱对不起我自己,我自己是很没耐心看源码的,看了两天之后发现你这篇文章,谢谢大佬。
  • 9bfc7878f5b3:感谢分享。加一句:对于不想保存临时状态的view,可以进行setSaveEnable()设置

本文标题:fragment的状态保存&恢复过程分析

本文链接:https://www.haomeiwen.com/subject/ctslrttx.html