2

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;
    }
});
matej_j
  • 21
  • 1
  • 5

1 Answers1

1

Add this method to your class which contains the above mentioned code.

static void updateUI() {
    if(mSharedPreferences.getInt(mSharedPrefKey,0) == 0){
        Log.d(TAG,"Shared preference stored 0");
        mBtHciSnoopLogServer.setChecked(false);
    }
}

And where you change the switch preference call the method:

  mSharedPreferences.edit().putInt(mSharedPrefKey, 0).commit();
  YourClass.updateUI();

As the method is static it is stored in global content so everything works fine.