My problem is - when I click on a <Switch>
, it gets toggled first and then the OnCheckedChangeListener
is called.
What I would like is this:
<Switch>
is clicked --> I show an AlertDialog --> If pressed yes or no --> Then flip ` with setChecked(boolean), [boolean = true if pressed yes, and false if pressed no].
Problem: When <Switch>
is clicked, it gets flipped automatically. I want to qualify it with a yes or no from a AlertDialog first.
sw_enableDisable
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
getActivity());
alertDialogBuilder
.setMessage(
"Sure you want to enable?. ")
.setCancelable(true)
.setPositiveButton(
getString("YES"),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
})
.setNegativeButton(
getString("NO"),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
sw_enDis_alreadyClicked = true;
} else {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
getActivity());
alertDialogBuilder
.setMessage(
"Sure you want to disable?")
.setCancelable(true)
.setPositiveButton(
getString("YES"),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
})
.setNegativeButton(
getString("NO"),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
});
Try this code. It worked for me:
Use the following updated code.
So whenever the user clicks on
No
of theAlertDialog
, you're supposed to toggle the switch again by usingBut this would in turn call
onCheckedChanged()
and then it'd be cycle all over again. So to handle that, maintain a booleantoogledProgrammatically
and set it totrue
whenever you're toggling it in the code. And then when theonCheckedChanged()
is called, just check if it was toggled programmatically or not. If yes, then don't do anything, else show the alert.prevent switching by setting back state.
Try to use onClick:
Intercepting touch event will solve the problem. Return TRUE if don't want to send event forward to the system. I came up with below approach. Have tested, working as expected.