AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Are you sure you want to delete this item?"); builder.setCancelable(false); // disallow canceling the dialog builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // delete the item } }); builder.setNegativeButton("No", null); AlertDialog dialog = builder.create(); dialog.show();
AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Do you want to save your changes?"); builder.setCancelable(true); // allow canceling the dialog builder.setPositiveButton("Save", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // save changes } }); builder.setNegativeButton("Discard", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // discard changes } }); AlertDialog dialog = builder.create(); dialog.show();In this example, we create an AlertDialog asking the user if they want to save changes or discard them. We use setCancelable(true) to allow the user to cancel the dialog by pressing the back button or tapping outside the dialog. Overall, the setCancelable method is a powerful tool for developers to control the behavior of their Android application's dialog boxes, whether they need to make a dialog non-cancelable to prevent user errors or allow cancellation for user convenience.