我正在尝试处理 onSaveInstanceState
method in class View
(不是 the one in class Activity
)。该方法确实返回 Parcelable
.我自己推导了View
来自 ViewGroup
并覆盖该方法以保存我自己的状态。但是当要保存状态时,我得到了一个异常(exception):
java.lang.IllegalStateException:
Derived class did not call super.onSaveInstanceState()
这很对,但对我来说仅仅调用该方法似乎还不够。那么我应该怎么做呢?如果该方法将通过 Parcel
要写入,我可以简单地将同一个包裹传递给父类(super class),这样事情就会按顺序写入。但这是一个返回值。
我是否应该将这个返回的对象作为我自己的 Parcelable
表示的成员包括在内,并使用 Parcel.writeParcelable
如果需要,将它与我自己的数据一起编码?还是有更好的方法来处理父级调用和可打包对象的链接?如果是这样,在加载父类(super class)的实例状态时应该使用什么类加载器?
最佳答案
由于 zapl 没有将他的评论转化为答案,所以我这样做了。
is there some better way to handle parent invocation and chaining of parcelable objects?
实现此目的的规范方法是为派生自 View.BaseSavedState
的保存数据创建自己的类。 ,这又是从 AbsSavedState
派生的.您可以调用父类的 onSaveInstance
处理程序并将结果对象传递给您自己类的构造函数。恢复数据时,getSuperState
给出针对父类的实例。
典型的代码示例如下所示:
static class SavedState extends View.BaseSavedState {
// include own data members here
public SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
// read own data here
}
@Override public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
// write own data here
}
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) { return SavedState(in); }
public SavedState[] newArray(int size) { return new SavedState[size]; }
};
}
@Override public Parcelable onSaveInstanceState() {
SavedState state = new SavedState(super.onSaveInstanceState());
// set data members here
return state;
}
@Override public void onRestoreInstanceState(Parcelable parcelable) {
SavedState state = (SavedState)parcelable;
super.onRestoreInstanceState(state.getSuperState());
// restore from data members here
}
以上改编自this presentation由 Cyril Mottier 设计,但也应该与设计人员总体上打算如何使用此类非常接近。
Should I include this returned object as a member of my own
Parcelable
representation, and useParcel.writeParcelable
to marshal it along with my own data if needed?
虽然上面提到的似乎是首选,behind the scenes它也依赖于 writeParcelable
。因此,如果有理由不使用该基类,只需调用 writeParcelable
来存储父类(super class)的状态就可以了。
what class loader should I use when loading the instance state of the super class?
current implementation of AbsSavedState
确实使用 null
作为类加载器参数,导致使用默认类加载器。但是,该行代码标有 FIXME
注释,因此它可能有一天会更改。
关于android - 覆盖 onSaveInstanceState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19004722/