我正在实现我自己的自定义 DialogPreference 子类,它有一个用于持久化整数的 SeekBar。我对需要进入的内容onSaveInstanceState()
和onRestoreInstanceState()
. 具体来说,您是否需要更新用户与之交互的 UI 小部件(在我的例子中是 SeekBar 小部件)onRestoreInstanceState()
?
我感到困惑的原因是这里的 API 文档文章告诉你这样做:
@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)的源代码,UI 小部件没有在onRestoreInstanceState()
. 只有 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 小部件(如果我应该更新它......)?