我正在实现自己的自定义DialogPreference子类,其中包含一个SeekBar用于持久化整数。我有点困惑需要在onSaveInstanceState()和onRestoreInstanceState()中添加什么内容。具体来说,在onRestoreInstanceState()中是否需要更新用户交互的UI小部件(在我的情况下是SeekBar小部件)?
我感到困惑的原因是API文档文章here告诉你要这样做:
但是查看一些官方的Android Preference类(EditTextPreference和ListPreference)的源代码,UI小部件在
以下是EditTextPreference的相关源代码:
我感到困惑的原因是API文档文章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)的源代码,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小部件(如果需要更新的话...)?
setValue
和setMaxValue
方法是您在自定义的DialogPreference
中定义的吗?如果是,能否发布这些方法的代码? - whatyouhideDialogPreference.getValue()
从对话框内的某些View
中检索值,而当调用onSaveInstanceState
和onRestoreInstanceState
时,这些视图仍然是空指针。 - whatyouhide