Android AlertDialog Tutorial with Examples
1. Android AlertDialog
Android AlertDialog is a dialog that displays a message, and support 1, 2 or 3 buttons. It makes it easy to create a dialog with just a few lines of code.
AlertDialog includes 3 areas:
- Title area
- Content area
- Button area
Landscape screen
Portrait screen
Title area
Use the setTitle(), setIcon() methods to set title and icon for the dialog box, which will be viewed in the Title area. Otherwise, use the setCustomTitle(View) method if you would like to have a customized Title area.
Content area
The Content area can display a message, a list of options and so on.
Buttons area
This area has a maximum of 3 buttons: Positive button, Negative button, and Neutral button, in which the first 2 buttons support Text & Icon, while the Neutral button only supports Text, however, you can have the icon displayed with a little trick (See more in the example).
2. Example of AlertDialog (1)
Example preview:
AlertButtonExample0.java
package org.o7planning.alertdialogexample;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
public class AlertDialogExample0 {
public static void showAlertDialog(final Context context) {
final Drawable positiveIcon = context.getResources().getDrawable(R.drawable.icon_positive);
final Drawable negativeIcon = context.getResources().getDrawable(R.drawable.icon_negative);
final Drawable neutralIcon = context.getResources().getDrawable(R.drawable.icon_neutral);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// Set Title and Message:
builder.setTitle("Title").setMessage("This is a message");
//
builder.setCancelable(true);
builder.setIcon(R.drawable.icon_title);
// Create "Positive" button with OnClickListener.
builder.setPositiveButton("Positive", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(context,"You choose positive button",
Toast.LENGTH_SHORT).show();
}
});
builder.setPositiveButtonIcon(positiveIcon);
// Create "Negative" button with OnClickListener.
builder.setNegativeButton("Negative", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(context,"You choose positive button",
Toast.LENGTH_SHORT).show();
// Cancel
dialog.cancel();
}
});
builder.setNegativeButtonIcon(negativeIcon);
// Create "Neutral" button with OnClickListener.
builder.setNeutralButton("Neutral", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
Toast.makeText(context,"You choose neutral button",
Toast.LENGTH_SHORT).show();
}
});
builder.setNeutralButtonIcon(neutralIcon); // Not working!!!
// Create AlertDialog:
AlertDialog alert = builder.create();
alert.show();
}
}
3. Example of AlertDialog (2)
AlertDialogExample2.java
package org.o7planning.alertdialogexample;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
public class AlertDialogExample2 {
public static void showAlertDialog(final Context context) {
final Drawable positiveIcon = context.getResources().getDrawable(R.drawable.icon_positive);
final Drawable negativeIcon = context.getResources().getDrawable(R.drawable.icon_negative);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// Set Title and Message:
builder.setTitle("Confirmation").setMessage("Do you want to close this app?");
//
builder.setCancelable(true);
builder.setIcon(R.drawable.icon_title);
// Create "Yes" button with OnClickListener.
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(context,"You choose Yes button",
Toast.LENGTH_SHORT).show();
Activity activity = (Activity) context;
activity.finish();
}
});
builder.setPositiveButtonIcon(positiveIcon);
// Create "No" button with OnClickListener.
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(context,"You choose No button",
Toast.LENGTH_SHORT).show();
// Cancel
dialog.cancel();
}
});
builder.setNegativeButtonIcon(negativeIcon);
// Create AlertDialog:
AlertDialog alert = builder.create();
alert.show();
}
}
4. Example of AlertDialog (List)
This is an example of the AlertDialog with a list of different options for the user to select:
AlertDialogListExample.java
package org.o7planning.alertdialogexample;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
public class AlertDialogListExample {
public static void showAlertDialog(final Activity activity) {
final Drawable negativeIcon = activity.getResources().getDrawable(R.drawable.icon_negative);
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
// Set Title.
builder.setTitle("Select an Animal");
// Add a list
final String[] animals = {"Horse", "Cow", "Camel", "Sheep", "Goat"};
builder.setItems(animals, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String animal = animals[which];
dialog.dismiss(); // Close Dialog
// Do some thing....
// For example: Call method of MainActivity.
Toast.makeText(activity,"You select: " + animal,
Toast.LENGTH_SHORT).show();
// activity.someMethod(animal);
}
});
//
builder.setCancelable(true);
builder.setIcon(R.drawable.icon_title);
// Create "Cancel" button with OnClickListener.
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(activity,"You choose No button",
Toast.LENGTH_SHORT).show();
// Cancel
dialog.cancel();
}
});
builder.setNegativeButtonIcon(negativeIcon);
// Create AlertDialog:
AlertDialog alert = builder.create();
alert.show();
}
}
5. Example of AlertDialog (Single Choice)
AlertDialogSingleChoiceExample.java
package org.o7planning.alertdialogexample;
import android.app.Activity;
import android.content.DialogInterface;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import java.util.HashSet;
import java.util.Set;
public class AlertDialogSingleChoiceExample {
public static void showAlertDialog(final Activity activity) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
// Set Title.
builder.setTitle("Select an Animal");
// Add a list
final String[] animals = {"Horse", "Cow", "Camel", "Sheep", "Goat"};
int checkedItem = 3; // Sheep
final Set<String> selectedItems = new HashSet<String>();
selectedItems.add(animals[checkedItem]);
builder.setSingleChoiceItems(animals, checkedItem, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Do Something...
selectedItems.clear();
selectedItems.add(animals[which]);
}
});
//
builder.setCancelable(true);
builder.setIcon(R.drawable.icon_title);
// Create "Yes" button with OnClickListener.
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if(selectedItems.isEmpty()) {
return;
}
String animal = selectedItems.iterator().next();
// Close Dialog
dialog.dismiss();
// Do something, for example: Call a method of Activity...
Toast.makeText(activity,"You select " + animal,
Toast.LENGTH_SHORT).show();
}
});
// Create "Cancel" button with OnClickListener.
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(activity,"You choose Cancel button",
Toast.LENGTH_SHORT).show();
// Cancel
dialog.cancel();
}
});
// Create AlertDialog:
AlertDialog alert = builder.create();
alert.show();
}
}
6. Example of AlertDialog (Multi Choice)
AlertDialogMultiChoiceExample.java
package org.o7planning.alertdialogexample;
import android.app.Activity;
import android.content.DialogInterface;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import java.util.HashSet;
import java.util.Set;
public class AlertDialogMultiChoiceExample {
public static void showAlertDialog(final Activity activity) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
// Set Title.
builder.setTitle("Select an Animal");
// Add a list
final String[] animals = {"Horse", "Cow", "Camel", "Sheep", "Goat"};
final boolean[] checkedInfos = new boolean[]{false, false, false, true, false}; // Sheep
builder.setMultiChoiceItems(animals, checkedInfos, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
checkedInfos[which] = isChecked;
}
});
//
builder.setCancelable(true);
builder.setIcon(R.drawable.icon_title);
// Create "Yes" button with OnClickListener.
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Close Dialog
dialog.dismiss();
String s= null;
for(int i=0; i< animals.length;i++) {
if(checkedInfos[i]) {
if(s == null) {
s = animals[i];
} else {
s+= ", " + animals[i];
}
}
}
s = s == null? "":s;
// Do something, for example: Call a method of Activity...
Toast.makeText(activity,"You select " + s,
Toast.LENGTH_SHORT).show();
}
});
// Create "Cancel" button with OnClickListener.
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(activity,"You choose Cancel button",
Toast.LENGTH_SHORT).show();
// Cancel
dialog.cancel();
}
});
// Create AlertDialog:
AlertDialog alert = builder.create();
alert.show();
}
}
7. Example of customized Title Area
By applying the setCustomTitle(View) method, you can customize the Title area of AlertDialog:
And probably use Android Resource File in order to create the interface of the Title area.
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// Custom Title Area.
LayoutInflater inflater = context.getLayoutInflater();
View view = inflater.inflate(R.layout.layout_custom_title, null);
builder.setCustomTitle(view);
...
// Create AlertDialog:
AlertDialog alert = builder.create();
alert.show();
Alright, now let's create a Layout Resource File:
- File > New > Android Resource File
- File Name: layout_custom_title.xml
- Resource type: Layout
- Directory name: layout
Then design the interface of the Title area:
layout_custom_title.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/icon_title" />
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:background="#E3DCC4"
android:gravity="center"
android:text="This is the Title"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imageView" />
</androidx.constraintlayout.widget.ConstraintLayout>
AlertDialogCustomTitleExample.java
package org.o7planning.alertdialogexample;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
public class AlertDialogCustomTitleExample {
public static void showAlertDialog(final Activity context) {
final Drawable positiveIcon = context.getResources().getDrawable(R.drawable.icon_positive);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// Custom Title Area.
LayoutInflater inflater = context.getLayoutInflater();
View view = inflater.inflate(R.layout.layout_custom_title, null);
builder.setCustomTitle(view);
// Message.
builder.setMessage("This is AlertDialog with Custom Title Area");
//
builder.setCancelable(true);
builder.setIcon(R.drawable.icon_title);
// Create "OK" button with OnClickListener.
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.setPositiveButtonIcon(positiveIcon);
// Create AlertDialog:
AlertDialog alert = builder.create();
alert.show();
}
}
Android Programming Tutorials
- Configure Android Emulator in Android Studio
- Android ToggleButton Tutorial with Examples
- Create a simple File Finder Dialog in Android
- Android TimePickerDialog Tutorial with Examples
- Android DatePickerDialog Tutorial with Examples
- What is needed to get started with Android?
- Install Android Studio on Windows
- Install Intel® HAXM for Android Studio
- Android AsyncTask Tutorial with Examples
- Android AsyncTaskLoader Tutorial with Examples
- Android Tutorial for Beginners - Basic examples
- How to know the phone number of Android Emulator and change it
- Android TextInputLayout Tutorial with Examples
- Android CardView Tutorial with Examples
- Android ViewPager2 Tutorial with Examples
- Get Phone Number in Android using TelephonyManager
- Android Phone Call Tutorial with Examples
- Android Wifi Scanning Tutorial with Examples
- Android 2D Game Tutorial for Beginners
- Android DialogFragment Tutorial with Examples
- Android CharacterPickerDialog Tutorial with Examples
- Android Tutorial for Beginners - Hello Android
- Using Android Device File Explorer
- Enable USB Debugging on Android Device
- Android UI Layouts Tutorial with Examples
- Android SMS Tutorial with Examples
- Android SQLite Database Tutorial with Examples
- Google Maps Android API Tutorial with Examples
- Android Text to Speech Tutorial with Examples
- Android Space Tutorial with Examples
- Android Toast Tutorial with Examples
- Create a custom Android Toast
- Android SnackBar Tutorial with Examples
- Android TextView Tutorial with Examples
- Android TextClock Tutorial with Examples
- Android EditText Tutorial with Examples
- Android TextWatcher Tutorial with Examples
- Format Credit Card Number with Android TextWatcher
- Android Clipboard Tutorial with Examples
- Create a simple File Chooser in Android
- Android AutoCompleteTextView and MultiAutoCompleteTextView Tutorial with Examples
- Android ImageView Tutorial with Examples
- Android ImageSwitcher Tutorial with Examples
- Android ScrollView and HorizontalScrollView Tutorial with Examples
- Android WebView Tutorial with Examples
- Android SeekBar Tutorial with Examples
- Android Dialog Tutorial with Examples
- Android AlertDialog Tutorial with Examples
- Android RatingBar Tutorial with Examples
- Android ProgressBar Tutorial with Examples
- Android Spinner Tutorial with Examples
- Android Button Tutorial with Examples
- Android Switch Tutorial with Examples
- Android ImageButton Tutorial with Examples
- Android FloatingActionButton Tutorial with Examples
- Android CheckBox Tutorial with Examples
- Android RadioGroup and RadioButton Tutorial with Examples
- Android Chip and ChipGroup Tutorial with Examples
- Using image assets and icon assets of Android Studio
- Setting SD Card for Android Emulator
- ChipGroup and Chip Entry Example
- How to add external libraries to Android Project in Android Studio?
- How to disable the permissions already granted to the Android application?
- How to remove applications from Android Emulator?
- Android LinearLayout Tutorial with Examples
- Android TableLayout Tutorial with Examples
- Android FrameLayout Tutorial with Examples
- Android QuickContactBadge Tutorial with Examples
- Android StackView Tutorial with Examples
- Android Camera Tutorial with Examples
- Android MediaPlayer Tutorial with Examples
- Android VideoView Tutorial with Examples
- Playing Sound effects in Android with SoundPool
- Android Networking Tutorial with Examples
- Android JSON Parser Tutorial with Examples
- Android SharedPreferences Tutorial with Examples
- Android Internal Storage Tutorial with Examples
- Android External Storage Tutorial with Examples
- Android Intents Tutorial with Examples
- Example of an explicit Android Intent, calling another Intent
- Example of implicit Android Intent, open a URL, send an email
- Android Services Tutorial with Examples
- Android Notifications Tutorial with Examples
- Android DatePicker Tutorial with Examples
- Android TimePicker Tutorial with Examples
- Android Chronometer Tutorial with Examples
- Android OptionMenu Tutorial with Examples
- Android ContextMenu Tutorial with Examples
- Android PopupMenu Tutorial with Examples
- Android Fragments Tutorial with Examples
- Android ListView Tutorial with Examples
- Android ListView with Checkbox using ArrayAdapter
- Android GridView Tutorial with Examples
Show More