获取首选项.xml中定义的默认值



我想使用 AndroidPreferenceManager 从 myPreferences.xml 中检索默认值。我让它与 int 和字符串一起使用,但是如何从布尔值加载默认值?

来自帮助程序方法的代码片段:

public static void putPref(String key, String value, Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
public static String getPref(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
public static Boolean getPrefBoolean(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getBoolean(key, null);
}

来自我的首选项的代码片段:

<EditTextPreference
app:defaultValue="@string/value_content_id"
app:key="@string/key_device_id"
app:summary="@string/device_id"
app:title="@string/title_content_id" />

<Preference
app:key="key_wifi"
app:summary="WifiSettings"
app:title="Set Wifi"  />
<CheckBoxPreference
app:defaultValue="true"
app:key="@string/key_app_lock"
app:summary="@string/summary_app_lock"
app:title="@string/title_app_lock" />

目标是在尚未设置任何值时从 myPpreferences.xml 中获取默认值。它适用于字符串和整数,但如何与布尔值一起使用?有解决方法吗?有时默认值可能是字符串、int 或布尔值。我现在的问题是,SharedPreferences.getBoolean 不接受空值作为参数。我真正不想做的是在使用 get 时定义默认值。因为它已经在首选项中声明.xml。

我不完全确定你在问什么。但是,如果使用 SharedPreferences 上的 包含 方法检查首选项是否存在,则可以确定是否要在帮助程序方法中返回 null。

https://developer.android.com/reference/android/content/SharedPreferences.html#contains(java.lang.String(

最新更新