码迷,mamicode.com
首页 > 移动开发 > 详细

Android偏好设置(4)设置默认值

时间:2015-07-04 19:41:00      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:

Setting Default Values


The preferences you create probably define some important behaviors for your application, so it‘s necessary that you initialize the associated SharedPreferences file with default values for each Preference when the user first opens your application.

The first thing you must do is specify a default value for each Preference object in your XML file using theandroid:defaultValue attribute. The value can be any data type that is appropriate for the correspondingPreference object. For example:

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

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

 

Then, from the onCreate() method in your application‘s main activity—and in any other activity through which the user may enter your application for the first time—call setDefaultValues():

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

Calling this during onCreate() ensures that your application is properly initialized with default settings, which your application might need to read in order to determine some behaviors (such as whether to download data while on a cellular network).

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 theKEY_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.

Android偏好设置(4)设置默认值

标签:

原文地址:http://www.cnblogs.com/cocl/p/4621051.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!