Android AlertDialog Example

This article is about Android AlertDialog and how to use it in android application with simple examples.

AlertDialog

AlertDialog is a small window that prompts the user to make a decision or enter additional information.

A dialog does not fill the screen and is normally used for events that require users to take an action before they can proceed.

AlertDialog With Buttons

In AlertDialog, you can add three different action buttons:

Positive: You should use this to accept and continue with the action ( “OK” or “YES” action).

Negative: You should use this to cancel the action( “CANCEL” or “NO” action).

Neutral: You should use this when the user may not want to proceed with the action, but doesn’t necessarily want to cancel ( “Remind me later” action)

Note: You can only add one of each button type to the AlertDialog. That is, you cannot have more than one “positive” button.

The below code snippet is an example of AlertDialog which contains title, message and three buttons (Positive, Negative and Neutral).

//create an instance of AlertDialog.Builder
AlertDialog.Builder builder = new AlertDialog.Builder(this);

//set dialog properties
//Set the title displayed in the Dialog.
builder.setTitle(R.string.alert_dialog_title)
        //Set the icon to be used in the title.
        .setIcon(R.drawable.alert_icon)
        //Set the message to display in the Dialog.
        .setMessage(R.string.dialog_message);

//Set a listener to be invoked when the positive button of the dialog is pressed.
builder.setPositiveButton(R.string.dialog_btn_ok, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
        // User clicked OK button
        dialogInterface.dismiss();
        Toast.makeText(getApplicationContext(), "OK pressed ", Toast.LENGTH_SHORT).show();
    }
});

//Set a listener to be invoked when the negative button of the dialog is pressed.
builder.setNegativeButton(R.string.dialog_btn_cancel, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
        // User clicked CANCEL button
        dialogInterface.dismiss();
        Toast.makeText(getApplicationContext(), "CANCEL pressed ", Toast.LENGTH_SHORT).show();

    }
});

//Set a listener to be invoked when the neutral button of the dialog is pressed.
builder.setNeutralButton(R.string.dialog_btn_got_it, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
        // User clicked GOT IT button
        dialogInterface.dismiss();
        Toast.makeText(getApplicationContext(), "GOT IT pressed ", Toast.LENGTH_SHORT).show();

    }
});

//create an AlertDialog
AlertDialog alertDialog = builder.create();

//display the dialog on screen
alertDialog.show();

AlertDialog With List

There are three kinds of lists available with the AlertDialog APIs:

  • A single-choice list: To add a list of single-choice items in the dialog as the content, use setItems() method.
  • A single-choice list (radio buttons): To add a list of single-choice items(radio buttons) in the dialog as the content, use setSingleChoiceItems() method.
  • A multiple-choice list (checkboxes):To add a list of multiple-choice list (checkboxes) in the dialog as the content, use setMultiChoiceItems() method.

The below code snippet is an example of AlertDialog which contains title and single-choice list.

//create an instance of AlertDialog.Builder
AlertDialog.Builder builder = new AlertDialog.Builder(this);

//get string array (languages)
final String[] language = getResources().getStringArray(R.array.languages);

builder.setTitle(getText(R.string.select_language_title))

        //Set language(list of languages) to be displayed in the dialog as the content.
        .setItems(language, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int indexPosition) {

                // The 'indexPosition' argument contains the index position
                // of the selected item
                String selectedItem = Arrays.asList(language).get(indexPosition);
                Toast.makeText(getApplicationContext(), "Selected Language: " + selectedItem, Toast.LENGTH_LONG).show();

            }
        });

//create an AlertDialog
AlertDialog alertDialog = builder.create();

//display the dialog on screen
alertDialog.show();

AlertDialog With Custom Layout

Android AlertDialog allows you to set custom layout in a dialog.

If you want a custom layout in a dialog, create a layout and add it to an AlertDialog by calling setView() on your AlertDialog.Builder object.

The below code snippet is an example of AlertDialog with custom layout.

//create an instance of AlertDialog.Builder
AlertDialog.Builder builder = new AlertDialog.Builder(this);

//get view object represents custom layout of dialog.
View view = getLayoutInflater().inflate(R.layout.dialog_custom_layout, null);

//get button and spinner by its id from view object.
final Spinner spinner = view.findViewById(R.id.spinner);
Button btnOk = view.findViewById(R.id.btn_ok);

ArrayList<String> list = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.languages)));
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

//set adapter in spinner.
spinner.setAdapter(adapter);

//Sets a custom view to be the contents of the alert dialog.
builder.setView(view);

//create an AlertDialog
final AlertDialog dialog = builder.create();

//set click listener on OK button click
btnOk.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        dialog.dismiss();
        String selectedItem = (String) spinner.getSelectedItem();
        Toast.makeText(getApplicationContext(), "Selected Language: " + selectedItem, Toast.LENGTH_LONG).show();
    }
});

//display the dialog on screen
dialog.show();

Let’s understand different ways of implementing an AlertDialog in android application with a simple example.

Creating New Project

1. In Android Studio, go to File ⇒ New Project, fill all the details required to create a new project and then click on finish.

2. Open the layout file activity_main.xml and add the below code. This layout file consist of three buttons, AlertDialog With Buttons (show AlertDialog with buttons), AlertDialog With List (show AlertDialog with list), AlertDialog With Custom Layout (show AlertDialog with custom layout).

activity_main.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="wrap_content"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_adw_buttons"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/margin_15dp"
        android:layout_marginTop="@dimen/margin_30dp"
        android:layout_marginRight="@dimen/margin_15dp"
        android:layout_marginBottom="@dimen/margin_15dp"
        android:text="@string/alert_dialog_with_buttons"
        android:textSize="@dimen/textsize_18sp"
        app:layout_constraintBottom_toTopOf="@+id/btn_adw_list"
        android:textAllCaps="false"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_chainStyle="packed" />

    <Button
        android:id="@+id/btn_adw_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/margin_15dp"
        android:text="@string/alert_dialog_with_list"
        android:textSize="@dimen/textsize_18sp"
        android:textAllCaps="false"
        app:layout_constraintBottom_toTopOf="@+id/btn_adw_customlayout"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn_adw_buttons" />


    <Button
        android:id="@+id/btn_adw_customlayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/margin_15dp"
        android:text="@string/alert_dialog_with_custom_layout"
        android:textSize="@dimen/textsize_18sp"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn_adw_list" />


</androidx.constraintlayout.widget.ConstraintLayout>

3. Create a new layout file dialog_custom_layout.xml (layout->New->Layout Resource File) and add the below code. This layout file represents the custom layout of AlertDialog.

dialog_custom_layout.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"
android:layout_width="match_parent"
android:layout_height="wrap_content">


<Button
android:id="@+id/btn_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/margin_20dp"
android:layout_marginBottom="@dimen/margin_20dp"
android:text="@string/dialog_btn_ok"
android:textColor="@android:color/white"
android:textStyle="bold"
android:textSize="@dimen/textsize_15sp"
android:background="@android:color/holo_orange_dark"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/spinner" />

<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="@dimen/margin_20dp"
android:padding="@dimen/padding_12dp"
android:prompt="@string/dialog_btn_ok"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />

<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/holo_orange_dark"
android:padding="@dimen/padding_12dp"
android:text="@string/dialog_title"
android:textColor="@android:color/white"
android:textSize="@dimen/textsize_20sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />


</androidx.constraintlayout.widget.ConstraintLayout>

4. Open MainActivity.java and add the below code. This activity contains three buttons with click listener to show the different ways of implementing the AlertDialog.

MainActivity.java

package com.c1ctech.androidalertdialogdemo;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Arrays;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

Button btnAlertDialogWithButtons, btnAlertDialogWithList, btnAlertDialogWithCustomLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//get button by its id
 btnAlertDialogWithButtons = findViewById(R.id.btn_adw_buttons);
btnAlertDialogWithList = findViewById(R.id.btn_adw_list);
btnAlertDialogWithCustomLayout = findViewById(R.id.btn_adw_customlayout);

//set click listener on btnAlertDialogWithMessage button
 btnAlertDialogWithButtons.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
createAlertDialogWithButtons();
}
});

//set click listener on btnAlertDialogWithList button
 btnAlertDialogWithList.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
createAlertDialogWithList();
}
});

//set click listener on btnAlertDialogWithCustomLayout button
 btnAlertDialogWithCustomLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
createAlertDialogWithCustomLayout();
}
});

}

//create and show alert dialog with title, message, buttons(positive,negative and neutral).
 void createAlertDialogWithButtons() {

//create an instance of AlertDialog.Builder
 AlertDialog.Builder builder = new AlertDialog.Builder(this);

 //set dialog properties
 //Set the title displayed in the Dialog.
 builder.setTitle(R.string.alert_dialog_title)
//Set the icon to be used in the title.
 .setIcon(R.drawable.alert_icon)
//Set the message to display in the Dialog.
 .setMessage(R.string.dialog_message);

//Set a listener to be invoked when the positive button of the dialog is pressed.
 builder.setPositiveButton(R.string.dialog_btn_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// User clicked OK button
 dialogInterface.dismiss();
Toast.makeText(getApplicationContext(), "OK pressed ", Toast.LENGTH_SHORT).show();
}
});

//Set a listener to be invoked when the negative button of the dialog is pressed.
 builder.setNegativeButton(R.string.dialog_btn_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// User clicked CANCEL button
 dialogInterface.dismiss();
Toast.makeText(getApplicationContext(), "CANCEL pressed ", Toast.LENGTH_SHORT).show();

}
});

//Set a listener to be invoked when the neutral button of the dialog is pressed.
 builder.setNeutralButton(R.string.dialog_btn_got_it, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// User clicked GOT IT button
 dialogInterface.dismiss();
Toast.makeText(getApplicationContext(), "GOT IT pressed ", Toast.LENGTH_SHORT).show();

}
});

//create an AlertDialog
 AlertDialog alertDialog = builder.create();

//display the dialog on screen
 alertDialog.show();


}

//create and show alert dialog with title and single-choice list.
 void createAlertDialogWithList() {

//create an instance of AlertDialog.Builder
 AlertDialog.Builder builder = new AlertDialog.Builder(this);

//get string array (languages)
 final String[] language = getResources().getStringArray(R.array.languages);

builder.setTitle(getText(R.string.select_language_title))

//Set language(list of languages) to be displayed in the dialog as the content.
 .setItems(language, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int indexPosition) {

// The 'indexPosition' argument contains the index position
 // of the selected item
 String selectedItem = Arrays.asList(language).get(indexPosition);
Toast.makeText(getApplicationContext(), "Selected Language: " + selectedItem, Toast.LENGTH_LONG).show();

}
});

//create an AlertDialog
 AlertDialog alertDialog = builder.create();

//display the dialog on screen
 alertDialog.show();
}

//create and show alert dialog with custom layout.
 void createAlertDialogWithCustomLayout() {

//create an instance of AlertDialog.Builder
 AlertDialog.Builder builder = new AlertDialog.Builder(this);

//get view object represents custom layout of dialog.
 View view = getLayoutInflater().inflate(R.layout.dialog_custom_layout, null);

//get button and spinner by its id from view object.
 final Spinner spinner = view.findViewById(R.id.spinner);
Button btnOk = view.findViewById(R.id.btn_ok);

ArrayList<String> list = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.languages)));
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

//set adapter in spinner.
 spinner.setAdapter(adapter);

//Sets a custom view to be the contents of the alert dialog.
 builder.setView(view);

//create an AlertDialog
 final AlertDialog dialog = builder.create();

//set click listener on OK button click
 btnOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
String selectedItem = (String) spinner.getSelectedItem();
Toast.makeText(getApplicationContext(), "Selected Language: " + selectedItem, Toast.LENGTH_LONG).show();
}
});

//display the dialog on screen
 dialog.show();

}
}

Leave a Reply