使用下列更新的代码。sw_enableDisable
. setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (toogledProgrammatically) {
toogledProgrammatically = false;
} else {
if (isChecked) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
alertDialogBuilder
. setMessage(
"Sure you want to enable?.")
. setCancelable(true)
. setPositiveButton(
"YES",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
})
. setNegativeButton(
"NO",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
toogledProgrammatically = true;
sw_enableDisable.toggle();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
} else {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
alertDialogBuilder
. setMessage(
"Sure you want to disable?")
. setCancelable(true)
. setPositiveButton(
"YES",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
})
. setNegativeButton(
"NO",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
toogledProgrammatically = true;
sw_enableDisable.toggle();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
}
});
因此,每当用户单击 No的时,就应该使用sw_enableDisable.toggle();
但这又会叫 onCheckedChanged() 然后再一次循环。 所以,要处理这个问题,在你切换到代码时,维护一个布尔值 toogledProgrammatically 并将它的设置为 true 。 然后调用 onCheckedChanged() 时,只需检查它是否以编程方式被切换,或者。 如果是的话,不要做任何事,否则显示警报。if (toogledProgrammatically) {
toogledProgrammatically = false;
} else {
if (isChecked)
.
.
.