I have a SwitchPreference that displays AlertDialog onChange and would like to accept/reject the change depending on button clicked in AlertDialog (positive/negative).
If user attempts to change value to "true" the change should be accepted, otherwise AlertDialog should be shown and SwitchPreference change should be rejected. Only if user confirms AlertDialog (positive button) the SwitchPreference should be changed.
Below is the relevant part of my Activity class that extends PreferenceActivity. Values in SharedPreferences are actually updated as expected it is just that SwitchPreference does not change visibly (switch remains checked) - I have to re-open SettingsActivity to see the change (switch is unchecked).
final SwitchPreference passwordEnabled = (SwitchPreference) findPreference(PASSWORD_ENABLED);
passwordEnabled.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(final Preference preference, Object newValue) {
final Context c = getActivity();
if ((boolean) newValue) {
return true;
}
new AlertDialog.Builder(c)
// omitting non-relevant code
.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
((SwitchPreference) preference).setChecked(false);
preference
.getEditor()
.putBoolean(PASSWORD_ENABLED, false)
.commit();
preference.setSummary(R.string.disabled);
}
})
.setNegativeButton(getString(R.string.cancel), null)
.create().show();
return false;
}
});