AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setMessage("Are you sure you want to exit?").setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // exit the app } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // close the dialog box dialog.cancel(); } }); AlertDialog alert = alertDialogBuilder.create(); alert.show();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setMessage("Do you want to delete this item?").setCancelable(true) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // delete the item } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // close the dialog box dialog.cancel(); } }); AlertDialog alert = alertDialogBuilder.create(); alert.show();In this example, the `setCancelable` method is set to `true`, meaning that the user can cancel the dialog if they want to. The dialog displays a message asking if the user wants to delete an item, with options to either confirm or cancel.