Alert Dialog Tutorial With Example In Android Studio

Alert Dialog in an android UI prompts a small window to make decision on mobile screen. Sometimes before making a decision it is required to give an alert to the user without moving to next activity. To solve this problem alert dialog came into practise. For example you have seen this type of alert when you try to exit the App and App ask you to confirm exiting.
Alert Dialog Example In Android Studio


AlertDialog.Builder Components Used In Alert Dialog

AlertDialog.Builder is used to create an interface for Alert Dialog in Android for setting like alert title, message, image, button, button onclick functionality etc.

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

Alert Dialog ComponentsBelow are the components of Alert Dialog:

1. setTitle(CharSequence title) – This component is used to set the title of the alert dialog. It is optional component.

  // Setting Alert Dialog Title
        alertDialogBuilder.setTitle("Confirm Exit..!!!");

2. setIcon(Drawable icon) – This component add icon before the title. You will need to save image in drawable icon.

 // Icon Of Alert Dialog
        alertDialogBuilder.setIcon(R.drawable.question);

3. setMessage(CharSequence message) – This component displays the required message in the alert dialog.

  // Setting Alert Dialog Message
        alertDialogBuilder.setMessage("Are you sure,You want to exit");

4. setCancelable(boolean cancelable) – This component has boolean value i.e true/false. If set to false it allows to cancel the dialog box by clicking on area outside the dialog else it allows.

  alertDialogBuilder.setCancelable(false);

Custom Alert Dialog Component In Android Studio
5. setPositiveButton(CharSequence text, DialogInterface.OnClickListener listener) – This component add positive button and further with this user confirm he wants the alert dialog question to happen.

  alertDialogBuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                finish();
                            }
                        });

6. setNegativeButton(CharSequence text, DialogInterface.OnClickListener listener) – This component add negative button and further with this user confirm he doesn’t want the alert dialog question to happen.

alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(MainActivity.this,"You clicked over No",Toast.LENGTH_SHORT).show();
                            }
                        });

7. setNeutralButton(CharSequence text, DialogInterface.OnClickListener listener) – This component simply add a new button and on this button developer can set any other onclick functionality like cancel button on alert dialog.

 alertDialogBuilder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(getApplicationContext(),"You clicked on Cancel",Toast.LENGTH_SHORT).show();
                            }
                         });

Alert Dialog Example In Android Studio

Below is the example of Alert Dialog in which the functionality of Alert Dialog is defined over button click. In this example we have used a simple button and on that button click the alert dialog window will appear.

Below you can download code, see final output and step by step explanation of Alert Dialog example in Android Studio.

Download Code (Password: abhiandroid)

Alert Dialog Example In Android Studio
Step 1: Create a new project and name it AlertDialogExample.

Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following code:

Here we add the button UI on click of which alert dialog will appear. We also used textview for asking user to click on button.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.alertdialogexample.MainActivity">

    <Button
        android:text="@string/exit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:onClick="exit"
        android:textStyle="normal|bold" 
        style="@style/Widget.AppCompat.Button.Colored"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="131dp"/>

    <TextView
        android:text="@string/click_over_button_to_exit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="68dp"
        android:id="@+id/textView2"
        android:layout_above="@+id/button"
        android:layout_centerHorizontal="true"
        android:textSize="18sp"
        android:textStyle="normal|bold"
        android:gravity="center" />
</RelativeLayout>

Step 3 : Now open app -> java -> package -> MainActivity.java and add the below code.

In this step firstly AlertDialog.Builder is used to create a interface like setting alert title, message, image, button, button onclick functionality etc.

Important Note: Add a image to the drawable folder before setting the alert dialog icon.

package com.example.alertdialogexample;

import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void exit(View view){
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        // Setting Alert Dialog Title
        alertDialogBuilder.setTitle("Confirm Exit..!!!");
        // Icon Of Alert Dialog 
        alertDialogBuilder.setIcon(R.drawable.question);
        // Setting Alert Dialog Message
        alertDialogBuilder.setMessage("Are you sure,You want to exit");
        alertDialogBuilder.setCancelable(false);

                alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                finish();
                            }
                        });

                alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(MainActivity.this,"You clicked over No",Toast.LENGTH_SHORT).show();
                            }
                        });
                alertDialogBuilder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(getApplicationContext(),"You clicked on Cancel",Toast.LENGTH_SHORT).show();
                            }
                         });

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

Output:

Now run the App and click on the button. The alert dialog will appear asking user to confirm if he wants to exit App. If user click on ‘No’, he remains in the App and if he click on ‘Yes’ the user will get exit from the App.


Custom Alert Dialog:

The custom dialog uses DIALOG to create custom alert in android studio. Dialog display a small window i.e a popup which draws the user attention over the activity before they continue moving forward. For more details read custom dialog tutorial

Alert Dialog Vs Custom Alert Dialog in Android

  • Is this article helps you understand?
  • YES   NO

Leave a Reply

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



Continue Reading Below Tutorial

Subscribe and get access to the latest android tutorials, freebies, and lots more!

Android Developer Money eBook
One More Step...

Enter your email and I'll send you a FREE copy of Android Dev Dollaring eBook:
Send Me This eBook >>
We hate SPAM and promise to keep your email address safe.

Download Your Free Copy

Download this free eBook and Learn:
1. Different approach developer use to earn through App business
2. Learn how Android Developer can generate passive income
3. Job is not the only option and you can choose freelancing
Send Me This eBook >>
One More Step...

Enter your email and I'll send you a FREE copy of Android Dev Dollaring eBook:
Send Me This eBook >>
We hate SPAM and promise to keep your email address safe.