Android Alertdialog Example: Creating Your Own Alerts

android alertdialog exampleAndroid usage on smartphones is increasing every day. Android is open source and is being constantly improved to provide better experience for users. This technology enables the development of powerful apps and games. It’s compatible with a wide range of hardware devices.   The reasons behind Android’s considerable popularity are its powerful features and ease of use. Android offers excellent support for multitasking and graphics. This technology was specifically designed for touchscreen devices such as smartphones and tablets. Now’s a good time to be part of the Android story. This course is a great place for beginners to learn about Android development.

Today we introduce you to an interesting feature of the Android programming language called AlertDialog. We’ll be showing you some examples, along with the code. Since it is based on the Java Programming language, you may want to brush up your Java fundamentals for Android, with this course.

What is AlertDialog Box

Android Alert dialog is used in many android applications. This dialog displays alerts to the users and is used to get confirmation from the users. An Alert dialog has three parts.

  1. Title: Note that title is optional.
  2. Content: This displays the message to the user. It can be a string message or a list or custom layout.
  3. Action Button(s): This button is of three types. They are Positive, Negative and Neutral action buttons. An alert dialog can have maximum three action buttons. If you want the user to accept the action, use Positive action button. It is normally displayed as OK/YES. If the user wants to cancel the action , then you can use Negative action button (NO). If the user wants to postpone the decison use Neutral action button (Later).

Methods used to add an Alert dialog

To add action button to the Alert dialog, the you have to use the following methods.

  • setPositiveButton (CharSequence text, DialogInterface.OnClickListener listener): The first argument is the text to be displayed. The second argument is the listener to be invoked when the positive button is pressed.
  • setNegativeButton (CharSequence text, DialogInterface.OnClickListener listener): The arguments are the same as the setPositiveButton method. However, the second argument is applicable when the negative button is pressed.
  • setNeutralButton (CharSequence text, DialogInterface.OnClickListener listener): The arguments are same as the SetPositiveButton method.

You may also want to check out this course to help understand Android dialog boxes better.

Code to build an AlertDialog Object

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_message)
.setTitle(R.string.dialog_title);
AlertDialog dialog = builder.create();

The first line creates an AlertDialog.builder object and then its constructor is called. The second line sets the message and the dialog of the object. Finally, we use the create function to create an AlertDialog box.

AlertDialog Class

In order to create the Alert dialog, you can use the AlertDialog.Builder class. The AlertDialog class is a subclass of the Dialog class. It is used to display one, two or three buttons.

Important functions of the AlertDialog class

  • AlertDialog(Context context)- Here Context refers to the application environment.
  • getButton(int whichButton)- The whichButton stands for the identifier of the button. This function will return one of the buttons used in the dialog. It will return null if the button doesn’t exist.
  • getListView()- Use this function to get the list view used in the dialog.
  • setButton(int whichButton, CharSequence text, DialogInterface.OnClickListener listener)- Use this function when you want a listener to be invoked when the positive button is selected.
  • setButton(int whichButton, CharSequence text, Message msg)-This function defines the message to be sent when a button is pressed.
  • setIcon(int resId)-This function is called with resId set to 0 if you don’t want to display an icon.
  • setMessage(CharSequence message)- Use this function to display a string in the dialog box.
  • setTitle (CharSequence title)- Use this method to add title to the dialog box.

Once you are familiar with the methods of AlertDialog, you can create your own dialog boxes. Here we have put together a few examples based on this class.

Example 1 – Program to Create Android Alert Dialog with One Button

AndroidAlert 1

AlertDialog alertDialog = new AlertDialog.Builder(
AlertDialogActivity.this).create();
alertDialog.setTitle("Alert Dialog");
alertDialog.setMessage("Welcome to AndroidHive.info");
alertDialog.setIcon(R.drawable.tick);
 alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();

This is a simple alertDialog. You’ll notice some of the functions we introduced to you in this tutorial. However, to learn more about writing your own code for Android, you can take this course.

Example 2 : Two Button Alertdialog Box

Similar to the One button, you can also create two or three button dialogs. In order to create a two button dialog box, you can add this code to the program mentioned above.

alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
}
});

The image given is the output for the Two button AlertDialog box.

AndroidAlert2

 Example 3: Three Button to AlertDialog Box

Similarly to create the three button alert dialog box, you have to write the code given in the previous examples along with the below code.

alertDialog.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "You clicked on Cancel",
Toast.LENGTH_SHORT).show();
}
});

Here is the output for the three button AlertDialog box.

AndroidAlert3

[Code snippets and images from AndroidHive]

Now lets move on to another interesting example which displays the alert with single option.

Example 4: AlertDialog Box with Single Option

Final CharSequence[] items = {"Red", "Green", "Blue"};
 AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Exit!")
.setSingleChoiceItems(items, 1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
 builder.create().show();

 Image Alert with single option

In this program, the programmer has used setSingleChoiceItems() method. The first argument refers to the items to be displayed in the dialog as the content. The second argument specifies which item is checked. The third argument is the listener which is notified when the item on the list is clicked. Here is the image of the output.

Now lets move on to another example.

Example 5: AlertDialog Box with Multiple Choices

final CharSequence[] items = {"Red", "Green", "Blue"};
final boolean [] selected = {true, false, true};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick colors")
.setMultiChoiceItems(items, selected, new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialogInterface, int item, boolean b) {
Log.d("Myactivity", String.format("%s: %s", items[item], b));
}
});
 builder.create().show();

In this program,  setMultiChoiceItems() method is called. The second argument of this method specifies which items are checked.  The output of the code is shown below.

Custom Dialog Box

It is possible to have a custom layout in the dialog box. For that you have to create a layout first. Then call the setView() of the AlertDialog box. This will add the layout to a AlertDialog. By default, the custom layout completely occupies the dialog window. However, you can use AlertDialog.Builder methods to add buttons and a title.

Hope this article gave you a better understanding of AlertDialog and its applications. Programming is best learned by creating your own programs. So do experiment with the code and try out various options on your own. If you need help at any point of time, you can refer back to this Android app development course.