これを行うには、クラスを実装View#onSaveInstanceState
およびView#onRestoreInstanceState
拡張しView.BaseSavedState
ます。
public class CustomView extends View {
private int stateToSave;
...
@Override
public Parcelable onSaveInstanceState() {
//begin boilerplate code that allows parent classes to save state
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
//end
ss.stateToSave = this.stateToSave;
return ss;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
//begin boilerplate code so parent classes can restore state
if(!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
SavedState ss = (SavedState)state;
super.onRestoreInstanceState(ss.getSuperState());
//end
this.stateToSave = ss.stateToSave;
}
static class SavedState extends BaseSavedState {
int stateToSave;
SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
this.stateToSave = in.readInt();
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(this.stateToSave);
}
//required field that makes Parcelables from a Parcel
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];
}
};
}
}
作業は、View と View の SavedState クラスの間で分割されます。との間で読み書きするすべての作業をクラスParcel
で行う必要があります。SavedState
その後、View クラスは状態メンバーを抽出し、クラスを有効な状態に戻すために必要な作業を実行できます。
注: View#onSavedInstanceState
andは、値 >= 0 を返すView#onRestoreInstanceState
場合に自動的に呼び出されます。これは、xml で ID を指定するか、手動で呼び出すと発生します。それ以外の場合は、取得したパーセルに返された Parcelableを呼び出して書き込み、状態を保存し、その後それを読み取ってfromに渡す必要があります。View#getId
setId
View#onSaveInstanceState
Activity#onSaveInstanceState
View#onRestoreInstanceState
Activity#onRestoreInstanceState
これの別の簡単な例は、CompoundButton