Android Preference默认值设置

在XML文件(advanced_preferences.xml)中为Preference设置默认值

<!-- default value is a boolean -->
<CheckBoxPreference
    android:defaultValue="true"
    ... />

<!-- default value is a string -->
<ListPreference
    android:defaultValue="@string/pref_syncConnectionTypes_default"
    ... />

在代码中还需要调用

PreferenceManager.setDefaultValues(this, R.xml.advanced_preferences, false);

第三个参数接受一个BOOL值,含义如下:

true:每次调用setDefaultValues都会导致Preference的初始化。
false:只初始化一次,重复调用setDefaultValues不会导致重复初始化。

PreferenceManager.setDefaultValues() This method takes three arguments:

  • Your application Context.

  • The resource ID for the preference XML file for which you want to set the default values.

  • A boolean indicating whether the default values should be set more than once.

  • When false, the system sets the default values only if this method has never been called in the past (or the KEY_HAS_SET_DEFAULT_VALUES in the default value shared preferences file is false).

As long as you set the third argument to false, you can safely call this method every time your activity starts without overriding the user’s saved preferences by resetting them to the defaults. However, if you set it to true, you will override any previous values with the defaults.