Default value of Android preference

 ̄綄美尐妖づ 提交于 2019-12-03 06:47:43

问题


How do you get the default value of an Android preference defined in XML? I don't want to repeat the definition of the default value in both the code and the preferences XML.


回答1:


You can define default value in resources (/values/bool.xml):

<resources>
    <bool name="mypreference_default">true</bool>
</resources>

Use the value in the preferences.xml:

<CheckBoxPreference
    android:defaultValue="@bool/mypreference_default"
    android:key="mypreference"
    android:title="@string/mypreference_title" />

Then use in code:

SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
Boolean value = context.getResources().getBoolean(R.bool.mypreference_default);
Boolean b = p.getBoolean("mypreference", value);



回答2:


First you need to define default values in your preference XML file. Then you can populate preferences with default values in your main Activity by calling:

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

When you need to retrieve a some preference just call:

int value = prefs.getInt("key", null);

Since your preferences are populated you won't get null value.




回答3:


Create integer.xml under res/values to store integer constants.

In prefereces.xml reference "@integer/default_brightness"

In code context.getResources().getInteger(R.integer.default_brightness)



来源:https://stackoverflow.com/questions/2767354/default-value-of-android-preference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!