Android 在主活动中从 XML 初始化首选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2874276/
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
Initialize preferences from XML in the main Activity
提问by pixel
My problem is that when I start application and user didn't open my PreferenceActivity
so when I retrieve them don't get any default values defined in my preference.xml file.
我的问题是,当我启动应用程序时,用户没有打开我的应用程序,PreferenceActivity
所以当我检索它们时,我的首选项.xml 文件中没有定义任何默认值。
preference.xml file:
首选项.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:key="applicationPreference" android:title="@string/config"
>
<ListPreference
android:key="pref1"
android:defaultValue="default"
android:title="Title"
android:summary="Summary"
android:entries="@array/entry_names"
android:entryValues="@array/entry_values"
android:dialogTitle="@string/dialog_title"
/>
</PreferenceScreen>
Snippet from my main Activity (onCreate
method):
来自我的主要活动(onCreate
方法)的片段:
SharedPreferences appPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String pref1 = appPreferences.getString("pref1", null);
In result I end up with a null
value.
结果我得到了一个null
值。
回答by Dave Webb
In onCreate()
of your main Activity
just call the PreferenceManager.setDefaultValues()
method.
在onCreate()
你的主要的Activity
只是调用的PreferenceManager.setDefaultValues()
方法。
PreferenceManager.setDefaultValues(this, R.xml.preference, false);
This will read your preference.xml
file and set the default values defined there. Setting the readAgain
argument to false
means this will only set the default values if this method has never been called in the past so you don't need to worry about overriding the user's settings each time your Activity
is created.
这将读取您的preference.xml
文件并设置在那里定义的默认值。将readAgain
参数设置为false
意味着这将仅在过去从未调用过此方法时设置默认值,因此您无需担心每次Activity
创建时覆盖用户的设置。
回答by yanchenko
I'll be brief. :)
我会简短。:)
strings.xml(actually I have prefs.xmlexclusively for preferences):
strings.xml(实际上我有专门用于首选项的prefs.xml):
<string name="pref_mypref_key">mypref</string>
<string name="pref_mypref_default">blah</string>
preferences.xml:
首选项.xml:
android:key="@string/pref_mypref_key"
android:defaultValue="@string/pref_mypref_default"
MyActivity.java:
我的活动.java:
String myprefVal = prefs.getString(getString(R.string.pref_mypref_key), getString(R.string.pref_mypref_default));
回答by CommonsWare
Your call to getString()
has null
as the second parameter. Change that to be the default value you want.
您的呼叫getString()
具有null
作为第二个参数。将其更改为您想要的默认值。