我有2个类ParentClass
和ChildClass
:ParentClass
是RelativeLayout的子类,它使用onSaveInstanceState()/onRestoreInstanceState()通过以下代码保存状态:
@Override
protected Parcelable onSaveInstanceState() {
SavedState savedState = new SavedState(super.onSaveInstanceState());
savedState.someObj = someObj;
savedState.someInt = someInt;
savedState.someEnum = someEnum;
return savedState;
}
@Override
protected void onRestoreInstanceState(Parcelable in) {
if (!(in instanceof SavedState)) {
super.onRestoreInstanceState(in);
return;
}
SavedState savedState = (SavedState) in;
super.onRestoreInstanceState(savedState.getSuperState());
this.someObj = savedState.someObj;
this.someInt = savedState.someInt;
this.someEnum = savedState.someEnum;
}
这是
SavedState
代码:public static class SavedState extends BaseSavedState {
private SomeObj someObj;
private int someInt;
private SomeEnum someEnum;
public SavedState(Parcelable superState) {
super(superState);
}
public SavedState(Parcel source) {
super(source);
someInt = source.readInt();
someEnum = SomeEnum.values()[source.readInt()];
someObj = source.readParcelable(SomeObj.class.getClassLoader());
}
@Override
public void writeToParcel(@NonNull Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(someInt);
dest.writeInt(someEnum.ordinal());
dest.writeParcelable(someObj, flags);
}
public static final Creator<SavedState> CREATOR = new Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
没什么好想的,当我直接使用此 View 时,一切都按预期工作(保存\恢复状态)。
然后,我有了
ChildClass
,它扩展了ParentClass
,它也使用完全相同的代码保存了状态,只是我只保存了long和int字段。当应用尝试通过从
ChildClass
中调用带有SavedState
的Parcel
构造函数来恢复CREATOR
View 状态时,它崩溃并显示以下堆栈:Caused by: android.os.BadParcelableException: ClassNotFoundException when unmarshalling: com.company.app.ParentClass$SavedState
1 android.os.Parcel.readParcelableCreator Parcel.java, line 2320
2 android.os.Parcel.readParcelable Parcel.java, line 2270
3 android.view.AbsSavedState.<init> AbsSavedState.java, line 57
4 android.view.View$BaseSavedState.<init> View.java, line 20128
5 com.company.app.ChildClass$SavedState.<init> ChildClass.java, line 151
6 com.company.app.ChildClass$SavedState$1.a ChildClass.java, line 166
7 com.company.app.ChildClass$SavedState$1.createFromParcel ChildClass.java, line 164
最佳答案
使您的 SavedState 类实现可拆分
public static class SavedState extends Parcelable {