3

I have switchpreference, when user change value I should show confirmation dialog and change value only if user click positive button, if user clicks negative value should not be changed.

3
  • call your confirmation inside the onPreferenceChange Commented Jun 27, 2016 at 8:51
  • 1
    No, it doesn't work. Because code after show() is executing and if I click negative button, switchpreference should be changed programmatically and after that onpreferencechange will be called Commented Jun 27, 2016 at 8:57
  • Did you find a solution for this? Commented Mar 7, 2017 at 12:18

2 Answers 2

1

Set OnPreferenceChangeListener of your preference and return false to suppress modification. Show a dialog and manually change your preference value from there.

val myPreference = preferenceScreen.findPreference<SwitchPreference>("my_pref_key")!!
myPreference.setOnPreferenceChangeListener { _, _ ->
        MaterialAlertDialogBuilder(context)/* ... */.setPositiveButton("Yes") { _, _ ->
                myPreference.isChecked = !myPreference.isChecked
        }.show()
        false // skip the default behavior 
}
Sign up to request clarification or add additional context in comments.

Comments

0

I think you can use alert dialog for confirmation with positive and negative buttons.

change value in positive button and leave code (do nothing) in negative button

  new AlertDialog.Builder(this).
                                        setTitle("title").setIcon(R.drawable.ic_launcher)
                                        .setMessage(getResources().getString(R.string.message))
                                        .setPositiveButton("Yes", new DialogInterface.OnClickListener()
                                        {
                                            public void onClick(DialogInterface dialog, int which) {

//change value here
                                            }
                                        }) .setNegativeButton("No", new DialogInterface.OnClickListener()
                                {
                                    public void onClick(DialogInterface dialog, int which) {
                                        // do nothing
                                    }
                                }).show();

1 Comment

I tried it, but in negative click we should revert value, because is was changed when onpreferenchechange called. As a result, in on negative click we should reveret changes and onpreferencehcnage will be called

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.