Android Dialog Example with Detailed Steps for Creation
Android 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.
- 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.
- 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.
- 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.
- Alert dialog: Here a dialog box comes with a title, can show up to three buttons and a list of selectable items. Also note that its layout can be customized.
- DatePickerDialog/TimePickerDialog: This dialog comes with a pre-defined user interface. You can choose a date or time. You can learn more about the Date/Time PickerDialog in this tutorial [Note to editor: Please add link to this article once it is published “Android Date Picker – Using Graphical Inputs”]
- ProgressDialog: It’s a dialog which displays a progress bar.
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.
- setIcon(Drawable icon): This function is used to include an icon in the alert dialog box.
- setCancelable(boolean cancelable): This function determines whether the dialog can be canceled or not.
- setMessage(CharSequence message): This is used to assign the message to be displayed in the dialog box.
- setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems, DialogInterface.OnMultiChoiceClickListener listener): This function determines the list of items to be displayed in the dialog. The listener is responsible for notifying the selected option.
- setOnCancelListener(DialogInterface.OnCancelListener onCancelListener): This method determines which event will be invoked if cancel button is selected in the dialog.
- setTitle(CharSequence title): This method determines the title to be displayed in the dialog box.
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
- Single choice list
- Radio buttons list- Here you can select only one option. The setSingleChoiceItems() method is used here.
- Checkboxes list- You have the choice to select multiple options. Here you have to use the setMultiChoiceItems() method.
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.
Recommended Articles
Top courses in Android Development
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.