Android Development
Alert Dialog
Android UI
Mobile Apps
Android Programming

How do I display an alert dialog on Android?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Displaying an alert dialog in an Android application is an essential task that allows developers to inform users, prompt users for decisions, or capture user input without navigating away from the current screen. This article delves into the technical intricacies of alert dialog implementation in Android using the AlertDialog class, provides illustrative examples, and presents a comparison of key dialog features through a structured table.

What is an Alert Dialog?

An alert dialog is a small window that prompts the user to make a decision or enter additional information. An alert dialog does not fill the screen and is typically used for simple notifications or for getting input from the user.

Basic Components of an Alert Dialog

  • Title: The header text of the dialog.
  • Message: A brief description or question for the user.
  • Button: Such as "OK", "Cancel", etc., for user actions.
  • Input Field: An optional field for user input.

Creating an Alert Dialog

In Android, an alert dialog is created by using the AlertDialog builder class. Here's a detailed walkthrough:

Step 1: Instantiate AlertDialog.Builder

To create an alert dialog, you need to have an instance of AlertDialog.Builder. The Builder class provides methods for configuring the dialog.

java
AlertDialog.Builder builder = new AlertDialog.Builder(context);

Step 2: Set the Dialog Properties

You set the text for the dialog title, message, and the buttons through the builder methods.

java
1builder.setTitle("Example Alert")
2       .setMessage("This is an example of an alert dialog.")
3       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
4           @Override
5           public void onClick(DialogInterface dialog, int which) {
6               // Handle the positive button click
7           }
8       })
9       .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
10           @Override
11           public void onClick(DialogInterface dialog, int which) {
12               // Handle the negative button click
13               dialog.dismiss();
14           }
15       });

Step 3: Create and Show the Dialog

After setting the properties, you call .create() to generate the AlertDialog and .show() to display it.

java
AlertDialog alertDialog = builder.create();
alertDialog.show();

Advanced Dialog Customization

Input Dialogs

For capturing user input, you can add an EditText to the dialog.

java
EditText input = new EditText(context);
builder.setView(input);

Custom Layouts

To use a custom layout, define your layout XML and inflate it in the dialog.

java
LayoutInflater inflater = getLayoutInflater();
View dialogLayout = inflater.inflate(R.layout.custom_dialog, null);
builder.setView(dialogLayout);

Dialog with a List

Here is how to show a list of items in a dialog:

java
1String[] items = {"Item 1", "Item 2", "Item 3"};
2builder.setItems(items, new DialogInterface.OnClickListener() {
3    @Override
4    public void onClick(DialogInterface dialog, int which) {
5        // Handle item click
6    }
7});

Style and Theme

You can style your dialog with theme attributes by passing a theme resource ID when creating the Builder instance.

java
AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.CustomDialogTheme);

Summary Table

The following table summarizes the key features and options for displaying an alert dialog in Android:

FeatureMethodDescription
TitlesetTitle(String title)Sets the title of the dialog.
MessagesetMessage(String message)Sets an informative message to be displayed.
Positive ButtonsetPositiveButton(String text,
DialogInterface.OnClickListener listener)Adds a button for a positive action.
Negative ButtonsetNegativeButton(String text,
DialogInterface.OnClickListener listener)Adds a button for a negative action.
Custom ViewsetView(View view)Uses a custom layout in the dialog.
List of ItemssetItems(String[] items,
DialogInterface.OnClickListener listener)Displays a list of items.
Theme & StyleTheme resource in constructorApplies custom styling to the dialog.

Conclusion

Displaying an alert dialog in Android is straightforward and highly customizable. By using the AlertDialog.Builder class, you can easily configure and display a dialog with various options, including title, message, buttons, lists, input fields, and custom views. Understanding how to leverage these capabilities can significantly improve your application's user interaction and feedback mechanisms.

By mastering alert dialogs in Android apps, you can enhance the user experience, ensuring that communications with users are both effective and engaging.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.