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

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.

转载于:https://www.cnblogs.com/sjjg/p/4621051.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值