Here is my solution for the first challenge of Chapter 31. My idea is to make Box class parcelable. To do this the Parcelable interface demands to implement following methods:
Firstly add implements Parcelable:
public class Box implements Parcelable
Next add required fields and methods:
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
mOrigin.writeToParcel(dest, flags);
mCurrent.writeToParcel(dest, flags);
}
// This is used for creating new box from Parcel object in createFromParcel function below
private Box (Parcel in) {
mOrigin.readFromParcel(in);
mCurrent.readFromParcel(in);
}
public static final Parcelable.Creator<Box> CREATOR = new Parcelable.Creator<Box>() {
/**
* Return a new box from the data in the specified parcel.
*/
public Box createFromParcel(Parcel in) {
Box b = new Box(in);
return b;
}
/**
* Return an array of boxes of the specified size.
*/
public Box[] newArray(int size) {
return new Box[size];
}
};
After that in the BoxDrawingView implement required methods:
@Override
protected Parcelable onSaveInstanceState() {
// Get state of the parent;
Parcelable parentState = super.onSaveInstanceState();
Bundle bundle = new Bundle();
bundle.putParcelable(PARENT_STATE_KEY, parentState);
bundle.putParcelableArray(BOXEN_KEY, mBoxen.toArray(new Box[mBoxen.size()]));
return bundle;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (state != null && state instanceof Bundle) {
Bundle bundle = (Bundle) state;
super.onRestoreInstanceState(bundle.getParcelable(PARENT_STATE_KEY));
Box[] boxes = (Box[]) bundle.getParcelableArray(BOXEN_KEY);
mBoxen = new ArrayList<>(Arrays.asList(boxes));
} else {
super.onRestoreInstanceState(state);
}
}
Im not sure if in method onRestoreInstanceState this if statement is required and the place where I’m calling super.onRestoreInstance is also good, but it works.