我正在實現自己的自定義DialogPreference子類,該子類具有用於保持整數的SeekBar。我有點困惑,需要進入onSaveInstanceState()
和onRestoreInstanceState()
。具體而言,您是否需要更新onRestoreInstanceState()
中與用戶交互的UI小部件(在我的示例中爲SeekBar小部件)?如何正確實現DialogPreference子類的onRestoreInstanceState()?
我感到困惑的原因是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偏好類(EditTextPreference和ListPreference),UI部件是沒有更新在onRestoreInstanceState()
。只有偏好的基礎值是(在上面的例子中,那將是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小部件(如果我應該更新它...)?
您在自定義的'DialogPreference'中定義了'setValue'和'setMaxValue'方法嗎?如果是這樣,你可以發佈這些方法的代碼? – whatyouhide
@whatyouhide是的。看到我更新的答案。 –
嗯,謝謝。我的問題是,我的'DialogPreference.getValue()'從對話框內的一些'View'中檢索值,當'onSaveInstanceState'和'onRestoreInstanceState'被調用時,這些視圖仍然是'null'指針。 – whatyouhide