初始化从XML preferences的主要活动 [英] Initialize preferences from XML in the main Activity

查看:148
本文介绍了初始化从XML preferences的主要活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是,当我启动应用程序和用户没有打开我的 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()活动的只需要调用<一href="http://developer.android.com/intl/de/reference/android/$p$pference/$p$pferenceManager.html#setDefaultValues%28android.content.Context,%20int,%20boolean%29">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.

这篇关于初始化从XML preferences的主要活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆