安卓preferences:如何当用户不使用preferences屏幕加载默认值? [英] Android Preferences: How to load the default values when the user hasn't used the preferences-screen?
问题描述
我使用的是preferenceActivity让用户设置一些值。 我喂养它的定义preferences XML文件。
I am using a PreferenceActivity to let the user set some values. I am feeding it the xml file with the defined preferences.
我已经将所有的机器人:设置defaultValue =
他们
当我开始我的应用程序,我需要preferences,或者如果它们还没有设置手动,我想要的默认值:
When I start my application, I need the preferences, or if they are not set yet manually, I want the default values:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean value = prefs.getBoolean("key"), false);
然而,当安卓设置defaultValue =真正的
我仍然得到假
。因此,它看起来像在XML设置defaultValues没有在任何地方使用,但初始化preferences屏幕时。
However, when android:defaultValue="true"
I still get false
. So, it looks like the defaultValues set in the XML are not used anywhere but when initializing the preferences-screen.
我不想为C在 getBoolean()
方法的默认值硬$ C $。那么,有没有办法得到默认值仅在1处确定这些?
I don't want to hardcode the default values in the getBoolean()
method. So, is there a way get the default-values with only defining these in 1 place?
推荐答案
这个问题我相似:
<一个href="http://stackoverflow.com/questions/2874276/initialize-$p$pferences-from-xml-in-main-activity">initialize-$p$pferences-from-xml-in-main-activity
只要使用这个code。在的onCreate
方法:
Just use this code in onCreate
method:
PreferenceManager.setDefaultValues(this, R.xml.preference, false);
这将载入您的preferences从XML和最后一个参数(<$ C C $> readAgain )将保证用户preferences将不会被覆盖。
It will load your preferences from XML, and last parameter (readAgain
) will guarantee that user preferences won't be overwritten.
看看成<一个href="http://developer.android.com/reference/android/$p$pference/$p$pferenceManager.html#setDefaultValues%28android.content.Context,%20int,%20boolean%29">$p$pferenceManager.setDefaultValues在进一步调查Android的API。
Take a look into PreferenceManager.setDefaultValues in Android API for further investigation.
这篇关于安卓preferences:如何当用户不使用preferences屏幕加载默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!