Android 偏好的默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2767354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:17:21  来源:igfitidea点击:

Default value of Android preference

androidandroid-preferences

提问by hpique

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.

如何获得 XML 中定义的 Android 首选项的默认值?我不想在代码和首选项 XML 中重复默认值的定义。

回答by Pawe? Nadolski

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

您可以在资源 ( /values/bool.xml) 中定义默认值:

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

Use the value in the preferences.xml:

使用 中的值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);

回答by pixel

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:

首先,您需要在首选项 XML 文件中定义默认值。然后,您可以通过调用在主 Activity 中使用默认值填充首选项:

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

由于您的偏好已填充,您将不会获得null价值。

回答by eugene

Create integer.xmlunder res/valuesto store integer constants.

创建integer.xmlunderres/values来存储整数常量。

In prefereces.xmlreference "@integer/default_brightness"

prefereces.xml参考"@integer/default_brightness"

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

在代码中 context.getResources().getInteger(R.integer.default_brightness)