Udemy logo

android dialog exampleAndroid is an open source Linux based operating system. It was specifically designed for mobile devices like smartphones and tablets. The Open Handset Alliance which is a consortium of companies such as Google and others spearhead the development of this popular software. One of the advantages of the Android technology is that it can be modified by anybody. As a result, vendors can change and enhance their products as they like.

In this beginners level tutorial, we introduce how to create the Android dialog box. We assume that you are familiar with the basics of the Java programming language. If not you may want to first check out Java essentials for Android with this course.

What is a Dialog Box?

A dialog box is used to prompt the user to make a decision. It normally occupies only a small part of a screen and requires the user to make a choice before proceeding.  To make programming easier, and uniform, a dialog box has various areas or sections predefined.

  1. Optional title area: The title is normally used to give a message or indicate what setting this dialog box is for. It’s your message to the user.
  2. Content area: This part is the actual content or options you want to give the user and can span a wide variety. It may be a slider, a picker, radio button, lists or from a range of many other things. For Alerts, it may simply be some text you want the user to be aware of.
  3. Action buttons: These are usually at the end of the dialog box and require user action or confirmation. These can be as simple as Yes and No buttons, or more complex, depending on the use case.

Alert dialog boxes are ones that simply inform the user of some condition, and require a simple acknowledgement in return. In these cases, the title area can be optional.

Popups are special light weight dialog boxes, which require a single selection from the user.

Toasts provide lightweight feedback about an operation, in a small popup. These do not require a user interaction and disappear on their own after a time out.

You can learn more about these in this Android development course.

How to Create a Dialog Box

You can instantiate a dialog box object from the various dialog classes in Android. There are different types of dialog classes as we shall see.

Dialog Fragment Class

You should use a DialogFragrament object to contain your dialog. This class provides the necessary controls to create and manage the appearance of the dialogue box. DialogFragment class enables you to use the dialog as an embeddable component in a larger view. An important feature of this class is that it handles lifecycle events such as the screen rotation in a proper manner. It also provides support to create your own customized dialog box.

To learn more about DialogFragments in Android, check out this course.

How to Create an Alert Dialog

 AlertDialog.Builder NewAlertDialog = new AlertDialog.Builder(this);

Here we create an object of AlertDialogBuilder class. The keyword ‘new ‘indicates the instantiation of a class. ‘This’ keyword refers to the present class. After this we need to assign values to the yes or no button. The following code does this

NewAlertDialog.setPositiveButton(CharSequence text, DialogInterface.OnClickListener listener)
NewAlertDialog.setNegativeButton(CharSequence text, DialogInterface.OnClickListener listener)

Here the setPositiveButton() sets a listener to be invoked by the event of pressing the positive button of the dialog. The same applies to the negative button.

There are other methods available which customize the alert dialog. We take a look at them.

Adding a List to AlertDialog Object

There are three type of list that you can create with the use of AlertDialog ApIs. They are as follows

Note that both traditional list and a radio buttons list give a single choice selection.However, its recommended to use the setSingleChoiceItems() method. The reason is if the dialog is reopened later it should display the current choice of the user.

Learn more about Android internals with this course.

Example: Program to Display an Alert Dialog Box

 private static final int DIALOG_ALERT = 20;
public void onClick(View view) {
  showDialog(DIALOG_ALERT);
}
@Override
protected Dialog onCreateDialog(int id) {
  switch (id) {
    case DIALOG_ALERT:
      Builder dialogbox = new AlertDialog.Builder(this);
      dialogbox.setMessage("This ends the activity");
      dialogbox.setCancelable(true);
      dialogbox.setPositiveButton("I agree", new OkOnClickListener());
      dialogbox.setNegativeButton("No, no", new CancelOnClickListener());
      AlertDialog xyz = dialogbox.create();
xyz.show();
  }
  return super.onCreateDialog(id);
}
private final class CancelOnClickListener implements
    DialogInterface.OnClickListener {
  public void onClick(DialogInterface dialog, int which) {
    Toast.makeText(getApplicationContext(), "Cancel selected, activity continues",
        Toast.LENGTH_LONG).show();
  }
}
private final class OkOnClickListener implements
    DialogInterface.OnClickListener {
  public void onClick(DialogInterface dialog, int which) {
    NewAlertActivity.this.finish();
  }
}

To learn more about how to write your own programs in Android, you can look up this course.

In this program, the builder class is used to create an alert dialog. Then we set the message, set whether the dialog is cancellable and the OK and Cancel buttons. In case the user presses the OK or cancel button there are event listeners to handle respective events. Finally, we use the create function to create a dialog box with the requisite properties. The show () function makes the created dialog box visible on the screen. The DialogInterface.OnClickListener is an interface which is used to run some code when an user click on any item on the dialog. A toast is a small popup that gives feedback about an operation. Also note that it automatically disappears after a specified timeframe. getApplicationContext() method gives the context of the application object of the current process.

The toast object is instantiated with the help of the makeText() method. This method requires three parameters. These are the application Context, the text message, and the duration for the toast.  The application Context is obtained by the getApplicationContext() method.The Toast.LENGTH_SHORT constant is used to show the view or text notification for a short time duration .The show() method of the toast object displays the view for the given duration. If OK is selected the finish function is called. The finish () is called to close the activity of the dialog box.

We hope this gives you fair idea about dialog boxes. Do experiment further on your own. If you need help at any point of time, you can refer back to this Android app development course.

Page Last Updated: May 2014

Top courses in Android Development

Dependency Injection in Android with Dagger 2 and Hilt
Vasiliy Zukanov
4.8 (2,199)
Bestseller
Android TDD Masterclass - Coroutines, Jetpack
Petros Efthymiou
4.5 (899)
Bestseller
The Complete Android Oreo Developer Course - Build 23 Apps!
Rob Percival, Nick Walter, Codestars • over 2 million students worldwide!
4.3 (17,560)
Full Android Development Masterclass | 14 Real Apps-46 Hours
Oak Academy, OAK Academy Team, Mehmet ÖNGEL
4.4 (789)
Mobile Penetration Testing of Android Applications
Gabriel Avramescu
4.5 (1,729)
Bestseller
Android Multithreading Masterclass
Vasiliy Zukanov
4.8 (897)
The Complete Android 12 & Kotlin Development Masterclass
Denis Panjuta, Tutorials.eu by Denis Panjuta
4.4 (11,792)
Bestseller

More Android Development Courses

Android Development students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.

Request a demo