我有一个PreferentFragment,其内容是从包含CheckBoxPreference的.xml文件中加载的
<CheckBoxPreference
android:title="@string/pref_secure_conn"
android:key="enable_secure_connection"
android:defaultValue="false"/>
如您所知,当用户与此首选项交互时,SharedPreferences对象会自动更新,以便android:key现在包含正确的布尔值。
但是,我想使用String而不是Boolean:是否有任何方法可以使CheckBoxPreference使用String值而不是Boolean值,以便以后可以使用该键调用getString?
目前,我只是在听'onSharedPreferenceChanged'并手动更改它,但是也许有更好的方法。(另一个明显的解决方法是在需要此值时使用getBoolean而不是getString,但让我们假设我无法做到这一点)
我想到的最简单的方法是继承CheckBoxPreference并保存Preference冗余:
package com.example.preferencestest;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.CheckBoxPreference;
import android.util.AttributeSet;
public class StringCheckBoxPreference extends CheckBoxPreference {
public StringCheckBoxPreference(Context context) { super(context); }
public StringCheckBoxPreference(Context context, AttributeSet attrs) { super(context, attrs); }
public StringCheckBoxPreference(Context context, AttributeSet attrs,
int defStyle) { super(context, attrs, defStyle); }
@Override
public void setChecked(boolean checked) {
super.setChecked(checked);
SharedPreferences p = getSharedPreferences();
SharedPreferences.Editor e = p.edit();
e.putString(getKey()+"asString", String.valueOf(checked));
e.apply();
}
}
您可以将此类添加到您的PreferencesActivity xml中,如下所示:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<com.example.preferencestest.StringCheckBoxPreference
android:defaultValue="true"
android:key="myCheckBox"
android:summary="@string/pref_description_social_recommendations"
android:title="@string/pref_title_social_recommendations"
/>
<CheckBoxPreference
android:defaultValue="true"
android:key="example_checkbox"
android:summary="@string/pref_description_social_recommendations"
android:title="@string/pref_title_social_recommendations" />
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句