Use the pit in CheckBoxPreference
Recently, I encountered some minor problems using CheckBoxPreference. Please note that it is convenient for people like me to step on the pit again in the future.
In the use of this component is found that the listening setOnPreferenceChangeListener doesn’t work, have no reaction, only when click on the Item, if it is click on the back of the icon is no reaction, can be said to be a bug system.
Check the source code and discover that the CheckBox does not set the listening event at all, so it must not be listening.
How to fix the problem, it can only be inheriting CheckBoxPreference, covering onBindView method, get the checkbox, set himself a setOnPerformCheckedChangeListener events, specific as follows:
public class SettingCheckBoxPreference extends CheckBoxPreference {
public SettingCheckBoxPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public SettingCheckBoxPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SettingCheckBoxPreference(Context context) {
super(context);
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
View checkboxView = view.findViewById(android.R.id.checkbox);
if(checkboxView ! =null && checkboxView instanceof SlidingButton) {
((SlidingButton) checkboxView).setOnPerformCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { callChangeListener(isChecked); setChecked(isChecked); }}); }}}Copy the code
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:title="@string/option_about" >
<com.xxx.view.SettingCheckBoxPreference
android:key="UserAgreementKey"
android:title="@string/revoke_title"
android:summary="@string/revoke_desc">
</com.xxx.view.SettingCheckBoxPreference>
</PreferenceScreen>
Copy the code