为什么onRestoreInstanceState在活动被销毁时调用了一个视图?

时间:2016-02-29 13:09:57

标签: android

在下面的堆栈跟踪中,您可以注意到,由于活动被销毁,将调用视图的onRestoreInstanceState。为什么这有必要?

    at com.mypackage.MyView.onRestoreInstanceState(Unknown Source)
    at android.view.View.dispatchRestoreInstanceState(View.java:13758)
    at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2889)
    at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2895)
    at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2895)
    at android.view.View.restoreHierarchyState(View.java:13736)
    at android.support.v4.app.Fragment.restoreViewState(Unknown Source)
    at android.support.v4.app.FragmentManagerImpl.moveToState(Unknown Source)
    at android.support.v4.app.FragmentManagerImpl.moveToState(Unknown Source)
    at android.support.v4.app.FragmentManagerImpl.moveToState(Unknown Source)
    at android.support.v4.app.FragmentManagerImpl.dispatchReallyStop(Unknown Source)
    at android.support.v4.app.FragmentActivity.onReallyStop(Unknown Source)
    at android.support.v4.app.FragmentActivity.doReallyStop(Unknown Source)
    at android.support.v4.app.FragmentActivity.onDestroy(Unknown Source)
    at android.support.v7.app.o.onDestroy(Unknown Source)
    at android.app.Activity.performDestroy(Activity.java:6189)
    at android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1164)
    at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3778)
    ... 10 more

修改

View.onRestoreInstanceState会收到View.onSaveInstanceState生成的内容。 onSaveInstanceState的文档说:“Hook允许视图生成其内部状态的表示,以后可用于创建具有相同状态的新实例。” - 当执行onDestroy时,不需要重新创建视图,那么为什么要调用onRestoreInstanceState?

2 个答案:

答案 0 :(得分:0)

片段onRestoreInstanceState作为活动onDestroy的一部分发生。

这是FragmentManagerImpl中的行为:

void moveToState(Fragment f, int newState, int transit, int transitionStyle, boolean keepActive) {
    //...
    case Fragment.CREATED:
    if (newState > Fragment.CREATED) {
    //...
        f.performActivityCreated(f.mSavedFragmentState);
        if (f.mView != null) {
            f.restoreViewState(f.mSavedFragmentState);
        }
        f.mSavedFragmentState = null;
    }
}

如果更改(移动)片段的状态且片段的视图不为null,则始终在此过程中调用restoreViewState。

也许您没有将super.onDestroy()作为onDestroy中的第一个语句?

答案 1 :(得分:0)

我认为问题应该是:片段被破坏后为什么savedInstanceState 不是 null