I am creating a custom view in android application. Custom view has Drawable object that is a vector image and is stored in folder res/drawable/ I want to save its state, so I create class SavedState that I use in methods onSaveInstanceState and onRestoreInstanceState.
private static class SavedState extends BaseSavedState {
Drawable picture;
Float degree = 0f;
public SavedState(Parcelable superState) {
super(superState);
}
public SavedState(Parcel source) {
super(source);
degree = source.readFloat();
picture= = source.readParcelable(getClass().getClassLoader());
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeFloat(degree);
out.writeParcelable((Parcelable) fly, flags);
}
public static final Parcelable.Creator<SavedState> CREATOR
= new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
@Nullable
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState myState = new SavedState(superState);
myState.degree = this.degree;
myState.picture = this.picture;
return myState;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
SavedState savedState = (SavedState) state;
super.onRestoreInstanceState(savedState.getSuperState());
this.degree = savedState.degree;
this. picture = savedState. picture;
invalidate();
}
However, when I launch the app and flip the phone screen, an error occurs:
java.lang.ClassCastException: android.graphics.drawable.VectorDrawable cannot be cast to android.os.Parcelable.
I have Android API 32 and Java 8.
I have tried to convert Drawable to Bitmap:
protected Parcelable onSaveInstanceState() {
// do not change the rest of the code
Bitmap bitmap = source.readParcelable(getClass().getClassLoader());
picture = new BitmapDrawable(bitmap);
}
public void writeToParcel(Parcel out, int flags) {
// do not change the rest of the code
Bitmap bitmap = ((BitmapDrawable) picture).getBitmap();
out.writeParcelable(bitmap, flags);
}
But the error remained, only now Drawable could not be cast to BitmapDrawable.
I have also tried to save the id of my Drawable object. But I can't use the method getResources a static context:
picture = getResources().getDrawable(id)
Maybe there is another way to save the Drawable object?