AlertDialogs are pop ups used to prompt a user about an action to be taken. An AlertDialog may also be used for other actions such as providing a list of options to choose from or can be customized to have a user provide unique details such as their login information or application settings.
Creating alert dialog is very easy. An Alertdialog is an extension of the Dialog class. It is capable of constructing most dialog user interfaces and is the suggested dialog type. You should use it for dialogs that use any of the following features:
- A title
- A text message
- One, two, or three buttons
To create an AlertDialog, use the AlertDialog.Builder subclass.
1 |
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); |
The following code will create alert dialog with tree button. setPositiveButton() is used to create a positive button, setNegativeButton() is used to invoke negative button and and setNeutralButton() is used to create a neutral cancel button to alert dialog.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public void alertThreeButtons() { new AlertDialog.Builder(MainActivity.this) .setTitle("Three Buttons") .setMessage("Where do you want to go?") .setIcon(R.drawable.ninja) .setPositiveButton("RIGHT", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { showToast("You want to go to the RIGHT."); dialog.cancel(); } }) .setNeutralButton("CENTER", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { showToast("You want to go to the CENTER."); dialog.cancel(); } }) .setNegativeButton("LEFT", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { showToast("You want to go to the LEFT."); dialog.cancel(); } }).show(); } |
Thanks