我能想到的最简单的方法是继承 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" />