Preference源码分析(1)

Preference状态恢复原理


0. 入口:PreferenceFragment.java

public void addPreferencesFromResource(@XmlRes int preferencesResId) {

requirePreferenceManager();

setPreferenceScreen(mPreferenceManager.inflateFromResource(getActivity(),

preferencesResId, getPreferenceScreen()));

}

1. PreferenceManager.java

public PreferenceScreen inflateFromResource(Context context, @XmlRes int resId,

PreferenceScreen rootPreferences) {

// Block commits

setNoCommit(true);

final PreferenceInflater inflater = new PreferenceInflater(context, this);

rootPreferences = (PreferenceScreen) inflater.inflate(resId, rootPreferences, true);

rootPreferences.onAttachedToHierarchy(this);

// Unblock commits

setNoCommit(false);

return rootPreferences;

}

2. GenericInflater(PreferenceInflater的父类)

private void rInflate(XmlPullParser parser, T parent, final AttributeSet attrs)

throws XmlPullParserException, IOException {

.......

if (onCreateCustomFromTag(parser, parent, attrs)) {

.......

}

if (DEBUG) {

((P) parent).addItemFromInflater(item);

......

}

其中parent就是PreferenceGroup

3. PreferenceGroup.java

public boolean addPreference(Preference preference) {

synchronized(this) {

    mPreferenceList.add(insertionIndex, preference);

}

preference.onAttachedToHierarchy(getPreferenceManager());

if (mAttachedToActivity) {

preference.onAttachedToActivity();

}


4. Preference.java

protected void onAttachedToHierarchy(PreferenceManager preferenceManager) {

mPreferenceManager = preferenceManager;

mId = preferenceManager.getNextId();

dispatchSetInitialValue();

}

private void dispatchSetInitialValue() {

// By now, we know if we are persistent.

final boolean shouldPersist = shouldPersist();

if (!shouldPersist || !getSharedPreferences().contains(mKey)) {

if (mDefaultValue != null) {

onSetInitialValue(false, mDefaultValue);

}

} else {

onSetInitialValue(true, null);

}

}


TwoStatePreference/MultiSelectListPreference/SeekBarPreference/YesNoPreference/EditTextPreference等都有onSetInitialValue的实现,比如:TwoStatePreference


@Override

protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {

setChecked(restoreValue ?getPersistedBoolean(mChecked)

: (Boolean) defaultValue);

}

protected boolean getPersistedBoolean(boolean defaultReturnValue) {

if (!shouldPersist()) {

return defaultReturnValue;

}

return mPreferenceManager.getSharedPreferences().getBoolean(mKey, defaultReturnValue);

}

至此,数据恢复了。

你可能感兴趣的:(Preference源码分析(1))