我创建SwitchPreference
来更改Android设置活动中的值。当用户更改SwitchPreference
值时,将调用'setOnPreferenceChangeListener()'函数。
现在,我显示了一个对话框提示,要求用户确认此操作。当用户单击肯定按钮时,它将正常工作。
但是问题是,每当用户选择否定确认按钮时。
在Android API 21中-对话框提示正常关闭。
在Android API 19中-对话框提示反复打开。
switchPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener(){
@Override
public boolean onPreferenceChange(Preference preference, final Object newValue) {
new EasyMaterialDialog.Builder(getActivity())
.title("Confirmation")
.content("Are you sure?")
.positiveText("Yes")
.negativeText("No")
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//Works Normally
}})
.onNegative(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//The problem is here
//The switchPreference value changed here again
//So once again setOnPreferenceChangeListener is called
switchPreference.setChecked(!(Boolean)newValue);
}
})
.cancelable(false)
.show();
return false;
}
});
每当用户单击否定按钮时,如何更改SwitchPreference的旧值?
最佳答案
您可以暂时“关闭”您的听众:switchPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, final Object newValue) { final Preference.OnPreferenceChangeListener that = this; new EasyMaterialDialog.Builder(getActivity()) ... .onNegative(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { switchPreference.setOnPreferenceChangeListener(null); switchPreference.setChecked(!(Boolean) newValue); switchPreference.setOnPreferenceChangeListener(that); } }) .show(); return false; }});