Android 如何获取特定偏好?

Don*_*rty 0 xml android preference android-preferences

我的应用程序在 res/xml/preferences.xml 中有以下代码:


<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="Wi-Fi settings">


   <EditTextPreference
            android:key="pref_voice_threshold_top"
            android:title="@string/title_pref_voicetopthreshold"
            android:dialogTitle="@string/dialog_title_pref_voicetopthreshold" 
            android:defaultValue="20"
            android:inputType="number"/>

</PreferenceCategory>

</PreferenceScreen>
Run Code Online (Sandbox Code Playgroud)

我想知道我是否可以在代码中使用此首选项,以便我可以通过下载 xml 文件来更新它?

因此,我目前在 PreferenceActivity 中显示上述首选项,效果很好,但是我希望能够通过每周从互联网下载新设置来更新设置。

所以我的问题是如何在代码中打开此首选项并将其值设置为新下载的值?

Tse*_*eng 5

正如 McStretch 所说,你必须获得优先权

sharedPreferences = getSharedPreferences("com.yourname.yourapp_preference", 0);
Editor editor = sharedPreferences.edit();

editor.putString("your_optionname", "newValue");
// Save
editor.commit();
Run Code Online (Sandbox Code Playgroud)

com.yourname.yourapp_preference 是 xml 文件的名称。它通常位于 /data/data/com.yourname.yourapp/shared_prefs/com.yourname.yourapp_preference.xml

只需检查该目录即可查看文件的命名方式,但基本上默认情况下它应该是 packagename_perference.xml