android - 在主 Activity 中从 XML 初始化首选项

标签 android xml android-preferences

我的问题是,当我启动应用程序并且用户没有打开我的 PreferenceActivity 所以当我检索它们时,没有在我的preference.xml 文件中定义任何默认值。

preference.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>

我的主要 Activity 的 fragment (onCreate 方法):

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

结果我得到一个 null 值。

最佳答案

在您的主 ActivityonCreate() 中,只需调用 the PreferenceManager.setDefaultValues() method .

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

这将读取您的 preference.xml 文件并设置其中定义的默认值。将 readAgain 参数设置为 false 意味着这只会在过去从未调用过此方法的情况下设置默认值,因此您无需担心覆盖用户的每次创建 Activity 时的设置。

关于android - 在主 Activity 中从 XML 初始化首选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2874276/

相关文章:

android httpGet问题

java - 使用 StAX 对 XML 文档进行小的修改

android - 自定义首选项标题字体大小大于 android 5 中的标准首选项

json - 如何在 Golang 中将 Json 字符串转换为 xml?

java - 什么样的循环适用于从 xml 输出标题和描述

android - 捕捉首选项点击事件的问题

java - 从 PreferenceActivity 启动 android Play Store 应用程序?

Android Telephony Stack 和 Dalvik 进程上下文

android - 以编程方式创建布局首选项

android - 如何使用Android Studio导出jar文件?