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
Default value of Android preference
提问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 null
value.
由于您的偏好已填充,您将不会获得null
价值。
回答by eugene
Create integer.xml
under res/values
to store integer constants.
创建integer.xml
underres/values
来存储整数常量。
In prefereces.xml
reference "@integer/default_brightness"
在prefereces.xml
参考"@integer/default_brightness"
In code context.getResources().getInteger(R.integer.default_brightness)
在代码中 context.getResources().getInteger(R.integer.default_brightness)