Implementuję własną niestandardową podklasę DialogPreference, która ma SeekBar używaną do utrzymywania liczby całkowitej. Jestem trochę zdezorientowany tym, co musi przejść w onSaveInstanceState()
i onRestoreInstanceState()
. W szczególności, czy musisz zaktualizować widget interfejsu użytkownika, z którym użytkownik wchodzi w interakcję (w moim przypadku widżet SeekBar) w wersji onRestoreInstanceState()
?Jak poprawnie wdrożyć onRestoreInstanceState() dla podklasy DialogPreference?
Powodem Jestem zmieszany jest to, że artykuł API doc here mówi ci to zrobić:
@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!
}
Ale patrząc na źródło dla niektórych oficjalnych Android klas Garaż (EditTextPreference i ListPreference), widżet UI jest niezaktualizowany w onRestoreInstanceState()
. Jedyną podstawową wartością preferencji jest (w powyższym przykładzie będzie to mNewValue
).
Oto istotne źródło 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!
}
Więc, co jest konsensus? Gdzie mam zaktualizować widget UI (jeśli mam go w ogóle zaktualizować ...)?
Czy zdefiniowano metody 'setValue' i' setMaxValue' w niestandardowym 'DialogPreference'? Jeśli tak, czy mógłbyś opublikować kod dla tych metod? – whatyouhide
@whatyouhide Tak. Zobacz moją zaktualizowaną odpowiedź. –
Mmmm, dziękuję. Mój problem polega na tym, że moje 'DialogPreference.getValue()' pobiera wartość z niektórych 'View's wewnątrz okna dialogowego, a te widoki są nadal wskaźnikami' null' gdy wywoływane są 'onSaveInstanceState' i' onRestoreInstanceState'. – whatyouhide