CheckBoxやRadioButtonはCompoundButtonを継承しているのですが、このコードを見ると以下のようにonSaveInstanceState()とonRestoreInstanceState()できちんと処理されています。
http://tools.oesf.biz/android-4.4.2_r1.0/xref/frameworks/base/core/java/android/widget/CompoundButton.java#364
364 @Override
365 public Parcelable onSaveInstanceState() {
366 // Force our ancestor class to save its state
367 setFreezesText(true);
368 Parcelable superState = super.onSaveInstanceState();
369
370 SavedState ss = new SavedState(superState);
371
372 ss.checked = isChecked();
373 return ss;
374 }
375
376 @Override
377 public void onRestoreInstanceState(Parcelable state) {
378 SavedState ss = (SavedState) state;
379
380 super.onRestoreInstanceState(ss.getSuperState());
381 setChecked(ss.checked);
382 requestLayout();
383 }
一方、CheckedTextViewではそのような処理は見あたりません。
http://tools.oesf.biz/android-4.4.2_r1.0/xref/frameworks/base/core/java/android/widget/CheckedTextView.java
なのでCheckedTextViewを継承して上記の処理を移植すれば、チェック状態を保持してくれるようになります。
public class CheckedTextView2 extends CheckedTextView {
public CheckedTextView2(Context context) {
super(context);
}
public CheckedTextView2(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CheckedTextView2(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
static class SavedState extends BaseSavedState {
boolean checked;
/**
* Constructor called from {@link CompoundButton#onSaveInstanceState()}
*/
SavedState(Parcelable superState) {
super(superState);
}
/**
* Constructor called from {@link #CREATOR}
*/
private SavedState(Parcel in) {
super(in);
checked = (Boolean) in.readValue(null);
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeValue(checked);
}
@Override
public String toString() {
return "CheckedTextView2.SavedState{"
+ Integer.toHexString(System.identityHashCode(this))
+ " checked=" + checked + "}";
}
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];
}
};
}
@Override
public Parcelable onSaveInstanceState() {
// Force our ancestor class to save its state
setFreezesText(true);
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.checked = isChecked();
return ss;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
setChecked(ss.checked);
requestLayout();
}
}
0 件のコメント:
コメントを投稿