Android Alert Dialog is one of the most important and basic component in Android applications. This dialog is used to show alerts to the users, get confirmation from the users.
This is a sample alert.
There are three parts in the alert dialog.
- Action Button(s)
In these three parts, ‘Title’ is an optional part.
This part is used to show the message to the user. In the sample alert dialog shown above ‘Sample One Action Button Alert’ is the content.
This content can be a string message or a list or any custom layout.
This is one of the important parts in the alert dialog. This is used to interact with the user. In the sample alert dialog shown above ‘OK’ is the action button.
Action buttons can be any one of the below three types;
Positive action button
Negative action button
Neutral action button
You can add all three types of action buttons to the Android alert dialog. It depends on the need. But you cannot add more than three action buttons in an alert dialog. Which means a particular type of action button cannot be added more than once.
So an alert dialog can have maximum of one positive, one negative and one neutral action button.
Normally positive action button is used to accept the action. (OK/YES)
Negative action is used to cancel the action. (NO)
Neutral action is used in neutral situations (May be later)
On newer devices using the Holo theme, the action button order (left to right) is now NEGATIVE - NEUTRAL – POSITIVE.
setPositiveButton(), setNegativeButton(), setNeutralButton() methods are used to add the respective action buttons to the alert dialog. These methods take two arguments.
- Text to be displayed in the action button
- DialogInterface.OnClickListener A method which will be executed on the click of the action button.
This is an optional part of the Android alert dialog. This is used to show simple messages.
AlertDialog.Builder class is used to create the alert dialog. AlertDialog class is a subclass of Dialog that can display one, two or three buttons.
If you only want to display a String in this dialog box, use the setMessage() method.
setTitle() method is used to add title to the alert dialog.
Calling show() method will make the alert dialog visible to the user.
Based on the number of action buttons available in the alert dialog, we can classify it as One button/two button/three button alert dialog.
In the below example I have shown all three types of alert dialogs.
Source code of this sample application: