android如何将View的状态特别保存为Preference?

时间:2016-12-01 07:34:33

标签: android sharedpreferences

在“设置”文档中,有一个onSaveInstanceState和onRestoreInstanceState的实现,其中包含一个名为SaveSatet的类。 它是如何工作的?谁有人向我解释?

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 = mNewValue;
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
mNumberPicker.setValue(myState.value);
}

0 个答案:

没有答案