【发布时间】:2013-01-06 11:56:48
【问题描述】:
我正在实现我自己的自定义 DialogPreference 子类,它有一个用于持久化整数的 SeekBar。我对onSaveInstanceState() 和onRestoreInstanceState() 需要输入的内容有点困惑。具体来说,您是否需要在onRestoreInstanceState() 中更新用户与之交互的 UI 小部件(在我的例子中是 SeekBar 小部件)?
我感到困惑的原因是API doc文章here告诉你这样做:
@Override
protected Parcelable onSaveInstanceState() {
final Parcelable superState = super.onSaveInstanceState();
if (isPersistent()) {
return superState;
}
final SavedState myState = new SavedState(superState);
myState.value = mNewValue; //<------------ saves mNewValue
return myState;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (state == null || !state.getClass().equals(SavedState.class)) {
super.onRestoreInstanceState(state);
return;
}
SavedState myState = (SavedState) state;
super.onRestoreInstanceState(myState.getSuperState());
mNumberPicker.setValue(myState.value); //<------------ updates the UI widget, not mNewValue!
}
但是查看一些官方 Android Preference 类(EditTextPreference 和 ListPreference)的源代码,onRestoreInstanceState() 中的 UI 小部件没有更新。只有 Preference 的基础值是(在上面的示例中,这将是 mNewValue)。
这里是 EditTextPreference 的相关来源:
@Override
protected Parcelable onSaveInstanceState() {
final Parcelable superState = super.onSaveInstanceState();
if (isPersistent()) {
return superState;
}
final SavedState myState = new SavedState(superState);
myState.value = getValue(); //<---- saves mValue
return myState;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (state == null || !state.getClass().equals(SavedState.class)) {
super.onRestoreInstanceState(state);
return;
}
SavedState myState = (SavedState) state;
super.onRestoreInstanceState(myState.getSuperState());
setValue(myState.value); //<---- updates mValue, NOT the UI widget!
}
那么,共识是什么?我应该在哪里更新 UI 小部件(如果我应该更新它的话......)?
【问题讨论】:
标签: android android-widget state android-preferences dialog-preference