1

我用两个 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);

}

}

我尝试了很多东西,但没有任何效果,一旦关闭我的应用程序,我就会失去我试图保存的首选项。

4

1 回答 1

0

您可以使用以下代码来保存您的偏好。不要忘记在自定义 Numberpicker 中添加 android:persistent="true"。

public class NumberPickerPreference extends DialogPreference{


private NumberPicker numberPicker;
private static int DEFAULT_VALUE = 2;
private int date;

public NumberPickerPreference(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

public NumberPickerPreference(Context context, AttributeSet attrs) {
    super(context, attrs);
}
@Override
protected View onCreateDialogView() {

    final FrameLayout parent = new FrameLayout(getContext());
    parent.addView(generateNumberPicker(), new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.WRAP_CONTENT,
            FrameLayout.LayoutParams.WRAP_CONTENT,
            Gravity.CENTER));

    return parent;
}

public NumberPicker generateNumberPicker() {
    numberPicker = new NumberPicker(getContext());
    numberPicker.setMinValue(1);
    numberPicker.setMaxValue(30);
    numberPicker.setValue(2);

    /*
     * Anything else you want to add to this.
     */

    return numberPicker;
}

@Override
protected void onDialogClosed(boolean positiveResult) {

    if (positiveResult) {
        persistInt(numberPicker.getValue());
    }
}

@Override
protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) {
    if (restorePersistedValue) {
        // Restore existing state
        date = this.getPersistedInt(DEFAULT_VALUE);
    } else {
        // Set default state from the XML attribute
        date = (Integer) defaultValue;
        persistInt(date);
    }
}

@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
    return a.getInteger(index,  DEFAULT_VALUE);
}

@Override
public void onClick(DialogInterface dialog, int which) {
    switch (which){
        case BUTTON_POSITIVE:
            setSummary(String.valueOf(numberPicker.getValue()));
            //Message.message(mContext,"ok clicked");
            break;

        case BUTTON_NEGATIVE:
            // Put your logic here for Cancel button press
            //Message.message(mContext, "cancel clicked");
            break;
    }
    super.onClick(dialog, which);
}

//  This code copied from android's settings guide.

private static class SavedState extends BaseSavedState {
    // Member that holds the setting's value
    // Change this data type to match the type saved by your Preference
    int value;

    public SavedState(Parcelable superState) {
        super(superState);
    }

    public SavedState(Parcel source) {
        super(source);
        // Get the current preference's value
        value = source.readInt();  // Change this to read the appropriate data type
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        super.writeToParcel(dest, flags);
        // Write the preference's value
        dest.writeInt(value);  // Change this to write the appropriate data type
    }

    // Standard creator object using an instance of this class
    public static final Parcelable.Creator<SavedState> CREATOR =
            new Parcelable.Creator<SavedState>() {

                public SavedState createFromParcel(Parcel in) {
                    return new SavedState(in);
                }

                public SavedState[] newArray(int size) {
                    return new SavedState[size];
                }
            };
}



@Override
protected Parcelable onSaveInstanceState() {
    final Parcelable superState = super.onSaveInstanceState();
    // Check whether this Preference is persistent (continually saved)
    if (isPersistent()) {
        // No need to save instance state since it's persistent, use superclass state
        return superState;
    }

    // Create instance of custom BaseSavedState
    final SavedState myState = new SavedState(superState);
    // Set the state's value with the class member that holds current setting value
    myState.value = date;
    return myState;
}

@Override
protected void onRestoreInstanceState(Parcelable state) {
    // Check whether we saved the state in onSaveInstanceState
    if (state == null || !state.getClass().equals(SavedState.class)) {
        // Didn't save the state, so call superclass
        super.onRestoreInstanceState(state);
        return;
    }

    // Cast state to custom BaseSavedState and pass to superclass
    SavedState myState = (SavedState) state;
    super.onRestoreInstanceState(myState.getSuperState());

    // Set this Preference's widget to reflect the restored state
    numberPicker.setValue(myState.value);
}
于 2015-08-19T02:57:04.180 回答