Android系统默认值preference默认值、系统、Android、preference

2023-09-05 01:54:18 作者:深情迎风散

你如何在XML中定义一个Android preference的默认值?

How do you get the default value of an Android preference defined in XML?

上下文:我不想在这两个code和preferences XML重复的默认值的定义

Context: 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:

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

使用中的值 preferences.xml

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

然后在code使用:

Then use in code:

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