开发者

Default value of Android preference

开发者 https://www.devze.com 2022-12-29 07:15 出处:网络
How do you get th开发者_如何学编程e 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.You can

How do you get th开发者_如何学编程e 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.


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);


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.


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消