要正确序列化和恢复带有变换的自定义视图的状态,你可以按照以下步骤操作:
public class CustomView extends View implements Parcelable {
// ... 自定义视图的代码
// 自动生成的Parcelable代码
protected CustomView(Parcel in) {
// 从Parcel中读取数据并恢复自定义视图的状态
}
public static final Creator CREATOR = new Creator() {
@Override
public CustomView createFromParcel(Parcel in) {
return new CustomView(in);
}
@Override
public CustomView[] newArray(int size) {
return new CustomView[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
// 将自定义视图的状态写入Parcel
}
}
int mCustomState
,你可以使用以下代码将其写入Parcel:@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mCustomState);
}
public static final Creator CREATOR = new Creator() {
@Override
public CustomView createFromParcel(Parcel in) {
return new CustomView(in);
}
@Override
public CustomView[] newArray(int size) {
return new CustomView[size];
}
};
protected CustomView(Parcel in) {
mCustomState = in.readInt();
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("custom_view_state", mCustomView);
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mCustomView = savedInstanceState.getParcelable("custom_view_state");
}
这样,你就可以正确地序列化和恢复带有变换的自定义视图的状态了。请注意,上述代码只是示例代码,你需要根据你的自定义视图的具体情况进行相应的修改。