AlertDialog in android

A dialog is a small window which is displayed above the main UI, in a part of the screen. It normally requires users to take an action before they can proceed (e.g. confirm an action, select an option, read alert message, etc.).

An AlertDialog has three regions:-

  1. Title: This is optional.
  2. Content Area: This can display a message, a list, or other custom layout.
  3. Action Buttons: There can be upto three action buttons in a dialog.

This code below will display an AlertDialog with three action buttons.

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
				builder.setTitle("Alert");
				builder.setMessage("The buttons below will Toast what you click.");
				builder.setPositiveButton("OPEN", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface _dialog, int id) {
						Toast.makeText(getApplicationContext(), "OPEN", Toast.LENGTH_LONG).show();
					}
				});
				builder.setNegativeButton("SHARE", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface _dialog, int id) {
						Toast.makeText(getApplicationContext(), "SHARE", Toast.LENGTH_LONG).show();
					}
				});
				builder.setNeutralButton("CANCEL", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface _dialog, int id) {
						_dialog.dismiss();
					}
				});
				builder.create().show();

This code below will display an AlertDialog on pressing back button and ask user to confirm exit from the app.

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
				builder.setTitle("Confirm");
				builder.setMessage("Are you sure you want to exit?");
				builder.setPositiveButton("EXIT", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface _dialog, int id) {
						finish();
					}
				});
				
				builder.setNeutralButton("CANCEL", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface _dialog, int id) {
						_dialog.dismiss();
					}
				});
				builder.create().show();