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 onPreferenceChangeSathish Kumar J– Sathish Kumar J2016-06-27 08:51:46 +00:00Commented Jun 27, 2016 at 8:51
-
1No, 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 calledPein– Pein2016-06-27 08:57:40 +00:00Commented Jun 27, 2016 at 8:57
-
Did you find a solution for this?CaptRisky– CaptRisky2017-03-07 12:18:36 +00:00Commented Mar 7, 2017 at 12:18
Add a comment
|
2 Answers
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
}
Comments
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
Pein
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