Android AlertDialog

Filed Under: Android

Android AlertDialog is used in cases when we require the user to choose an option from the prompt presented on the screen. In this tutorial we will be discussing about creating different Alert Dialog with one button (OK button), two buttons (Yes and No) and three buttons (Yes, No and Cancel).

Android AlertDialog

Below is the final android alert dialog application we will create in this tutorial.

android alertdialog example

Android AlertDialog is one of the most important and basic component in Android applications. Alert dialog box is used to show alerts to the users, get confirmation from the users. In order to make an alert dialog, we need to make an object of AlertDialogBuilder which is an inner class of AlertDialog. Its syntax is given below.


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

Android AlertDialog Components

  1. Title: Note that title is optional
  2. Content: This displays the message to the user. It can be a string message, a list or custom layout
  3. Action Buttons: These buttons are of three types. They are Positive, Negative and Neutral action buttons. An alert dialog can have maximum three action buttons. In general following are the conventions for the buttons:
    • If you want the user to accept the action, use Positive action button. It is normally displayed as OK/YES.
    • If the user wants to cancel the action, then you can use Negative action button (NO).
    • If the user wants to postpone the decision use Neutral action button (Later).

Now we need to set the methods of these buttons using AlertDialogBuilder class. The syntax is given below.


alertDialogBuilder.setPositiveButton(CharSequence text, DialogInterface.OnClickListener listener);
alertDialogBuilder.setNegativeButton(CharSequence text, DialogInterface.OnClickListener listener);
alertDialogBuilder.setNeutralButton(CharSequence text, DialogInterface.OnClickListener listener);

The first argument is the text to be displayed. The second argument is the listener to be invoked when the positive button is pressed.

AlertDialog Functions

Besides this, there are some functions available to customise the alert dialog as given below.

  1. setIcon(Drawable icon): This method set the icon of the alert dialog box
  2. setCancelable(boolean cancelable): This method sets the property that the dialog can be cancelled or not
  3. setMessage(CharSequence message): This method sets the message to be displayed in the alert dialog
  4. setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems, DialogInterface.OnMultiChoiceClickListener listener): This method sets list of items to be displayed in the dialog as the content. The selected option will be notified by the listener
  5. setOnCancelListener(DialogInterface.OnCancelListener onCancelListener): This method Sets the callback that will be called if the dialog is cancelled
  6. setTitle(CharSequence title): This method set the title to be appear in the dialog
  7. getListView(): This function is used to get the list view used in the dialog

After creating and setting the dialog builder, we need to create an alert dialog by calling the create() method of the builder class. Its syntax is shown below.


AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();

Android AlertDialog Example Project Structure

android alertdialog example

This application consists of three buttons which opens alert dialog containing the respective number of buttons.

Android Alert Dialog Project Code

The application consists of a single activity. The layout of the activity has three buttons as shown in the xml file below.

activity_alert.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".AlertActivity" >

    <Button
        android:id="@+id/one_button_alert"
        android:layout_width="200dip"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="25dip"
        android:layout_marginLeft="20dip"
        android:text="Single Button Alert" />
    <Button
        android:id="@+id/two_button_alert"
        android:layout_width="200dip"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@id/one_button_alert"
        android:layout_marginLeft="20dip"
        android:text="Two Buttons Alert" />
    <Button
        android:id="@+id/three_button_alert"
        android:layout_width="200dip"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@id/two_button_alert"
        android:layout_marginLeft="20dip"
        android:text="Three Buttons Alert" />
</RelativeLayout>

The AlertActivity.java is given below. Each button click invokes an alert dialog with different set of action buttons. On clicking action buttons a Toast corresponding to that action button is displayed.


package com.journaldev.alertdialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class AlertActivity extends Activity {
    private Button button1;
    private Button button2;
    private Button button3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alert);
        button1 = (Button) findViewById(R.id.one_button_alert);
        button2 = (Button) findViewById(R.id.two_button_alert);
        button3 = (Button) findViewById(R.id.three_button_alert);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        AlertActivity.this);
                builder.setTitle("Sample Alert");
                builder.setMessage("One Action Button Alert");
                builder.setPositiveButton("OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                Toast.makeText(getApplicationContext(),"Yes is clicked",Toast.LENGTH_LONG).show();
                            }
                        });
                builder.show();
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        AlertActivity.this);
                builder.setTitle("Sample Alert");
                builder.setMessage("Two Action Buttons Alert Dialog");
                builder.setNegativeButton("NO",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                Toast.makeText(getApplicationContext(),"No is clicked",Toast.LENGTH_LONG).show();
                            }
                        });
                builder.setPositiveButton("YES",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                Toast.makeText(getApplicationContext(),"Yes is clicked",Toast.LENGTH_LONG).show();
                            }
                        });
                builder.show();
            }
        });
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        AlertActivity.this);
                builder.setTitle("Sample Alert");
                builder.setMessage("Three Action Buttons Alert Dialog");
                builder.setNegativeButton("NO",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                Toast.makeText(getApplicationContext(),"No is clicked",Toast.LENGTH_LONG).show();
                            }
                        });
                builder.setPositiveButton("YES",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                Toast.makeText(getApplicationContext(),"Yes is clicked",Toast.LENGTH_LONG).show();
                            }
                        });
                builder.setNeutralButton("CANCEL",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                Toast.makeText(getApplicationContext(),"Cancel is clicked",Toast.LENGTH_LONG).show();
                            }
                        });

                builder.show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

}

This brings an end to this tutorial. We’ll discuss how to customize alert dialog at length later. You can download the final android alert dialog project from the below link.

Reference: Official Doc

Comments

  1. Sagar Avhad says:

    This article is really helpful. I used to refer this awesome site. Thank you so much.

  2. Rohit says:

    After Creating and setting alertDailog You instructed that we need to call Create() method But in your whole code you didn’t used create() method anywhere??

  3. kumar says:

    Hi, Could you please send the programs with question and answer to my email id : kumarkk3434@gmail.com. Thanks in advance

  4. jamaysha says:

    Thanks a lot , Its really very helpful tutorial for beginners.

  5. Mehran Negahbani says:

    This site is excellent. Keep on the good work and thank you all for providing all these codes.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages