Android Preference默认值设置


<!-- default value is a boolean -->
    ... />

<!-- default value is a string -->
    ... />


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



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.