Pein
Pein

Reputation: 1079

How to implement confirmation dialog for switchpreference in Android?

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.

Upvotes: 3

Views: 669

Answers (2)

Dmitry K
Dmitry K

Reputation: 95

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 
}

Upvotes: 1

Uma Achanta
Uma Achanta

Reputation: 3729

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();

Upvotes: 0

Related Questions