初始化从XML preferences的主要活动初始化、XML、preferences

由网友(地域再见行不行)分享简介:我的问题是,当我启动应用程序和用户没有打开我的 preferenceActivity 所以当我找回它们没有得到任何定义的默认值我preference.xml文件。My problem is that when I start application and user didn't open my Preference...

我的问题是,当我启动应用程序和用户没有打开我的 preferenceActivity 所以当我找回它们没有得到任何定义的默认值我preference.xml文件。

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.

preference.xml文件:

preference.xml file:

<?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>

片段从我的主要活动(的onCreate 法):

    SharedPreferences appPreferences = PreferenceManager.getDefaultSharedPreferences(this);        
    String pref1 = appPreferences.getString("pref1", null);

在结果,我结束了一个值。

In result I end up with a null value.

推荐答案

的onCreate()活动的只需要调用the preferenceManager.setDefaultValues​​()方法。

In onCreate() of your main Activity just call the PreferenceManager.setDefaultValues() method.

PreferenceManager.setDefaultValues(this, R.xml.preference, false);

这将读取你的 preference.xml 文件,并设置在那里定义的默认值。在 readAgain 参数设置为表示这只会设置的默认值,如果这种方法从来没有打电话过去所以你不必担心你的活动创建每次覆盖用户的设置。

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.

阅读全文

相关推荐

最新文章