我用两个 NumberPicker(在自定义类 MinuteSecondPicker 中)制作了一个自定义 DialogPreference。我为两个 numberPicker 选择值,当我再次打开我的 DialogPreference 时,我的值不会恢复(我想我会保存) persistString(String myValue)、shouldCommit 和 shouldPersist --> 全部返回 'TRUE' :
public class TimePreference extends DialogPreference {
private int lastMinute = Constante.DEFAULT_WATER_MINUTE; //10
private int lastSecond = Constante.DEFAULT_WATER_SECOND; //00
private MinuteSecondPicker minuteSecondPicker = null;
public static int getMinute(String time) {
String[] pieces=time.split(":");
return(Integer.parseInt(pieces[0]));
}
public static int getSecond(String time) {
String[] pieces=time.split(":");
return(Integer.parseInt(pieces[1]));
}
public TimePreference(Context ctxt, AttributeSet attrs) {
super(ctxt, attrs);
this.setPositiveButtonText(Constante.BT_VALIDER);
this.setNegativeButtonText(Constante.BT_ANNULER);
}
@Override
protected View onCreateDialogView() {
minuteSecondPicker = new MinuteSecondPicker(getContext());
return(minuteSecondPicker);
}
@Override
protected void onBindDialogView(View v) {
super.onBindDialogView(v);
minuteSecondPicker.getMinutePicker().setValue(lastMinute);
minuteSecondPicker.getSecondPicker().setValue(lastSecond);
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
lastMinute = minuteSecondPicker.getMinutePicker().getValue();
lastSecond = minuteSecondPicker.getSecondPicker().getValue();
String time = String.valueOf(lastMinute)+":"+String.valueOf(lastSecond);
//Insertion dans la persistence du téléphone
if(callChangeListener(time)){
persistString(time); //Return True
}
}
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return(a.getString(index));
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
String time = null;
int test = 0;
//recupération des valeurs stockées en persistence du mobile
if (restoreValue) {
if(defaultValue == null){
time = String.valueOf(Constante.DEFAULT_WATER_MINUTE)+":"+String.valueOf(Constante.DEFAULT_WATER_SECOND);
}else{
time = getPersistedString(defaultValue.toString());
}
}else{
time = defaultValue.toString();
}
lastMinute = getMinute(time);
lastSecond = getSecond(time);
}
}
我尝试了很多东西,但没有任何效果,一旦关闭我的应用程序,我就会失去我试图保存的首选项。