How to show/display Alert Dialog/Dialog in Android.

In this post, I will show you how to show alertDialog in Android. AlertDialog is used largely to show alerts or confirmation messages to the user. Alert Dialog is very easy to create.

So, Let’s Start:-

Simple AlertDialog with “OK” Button

//create alertDialogBuilder
     AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);

     // set title
     alertDialogBuilder.setTitle("CoderzPassion");

     // set dialog message
     alertDialogBuilder
             .setMessage("Welcome To CoderzPassion!Keep Visting for Android Tutorials")
             .setCancelable(false)
             .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int id) {
                     // if this button is clicked, do something here i am displaying Toast Message

                     Toast.makeText(MainActivity.this, "You clicked On Ok Button ", Toast.LENGTH_SHORT).show();
                 }
             });

     // create alert dialog
     AlertDialog alertDialog = alertDialogBuilder.create();

     // show it
     alertDialog.show();

AlertDialog with “Two” Buttons

//create alertDialogBuilder
       AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);

       // set title
       alertDialogBuilder.setTitle("Your Title");

       // set dialog message
       alertDialogBuilder
               .setMessage("Click yes to exit!")
               .setCancelable(false)
               .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       // if this button is clicked,  do something here i am displaying Toast Message
                       Toast.makeText(MainActivity.this, "You clicked On Yes ", Toast.LENGTH_SHORT).show();
                   }
               })
               .setNegativeButton("No", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       // if this button is clicked, just close
                       // the dialog box and do nothing
                       dialog.cancel();
                   }
               });

       // create alert dialog
       AlertDialog alertDialog = alertDialogBuilder.create();

       // show it
       alertDialog.show();

AlertDialog with Three Button (One Neutral Button)

//create alertDialogBuilder
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);

        // set title
        alertDialogBuilder.setTitle("Your Title");

        // set dialog message
        alertDialogBuilder
                .setMessage("Click yes to exit!")
                .setCancelable(false)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // if this button is clicked,  do something here i am displaying Toast Message
                        Toast.makeText(MainActivity.this, "You clicked On Yes ", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //cancel the dialog box
                        dialog.cancel();
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // if this button is clicked,  do something here i am displaying Toast Message
                        Toast.makeText(MainActivity.this, "You clicked On No ", Toast.LENGTH_SHORT).show();

                    }
                });

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();

 Creating Custom Dialog

layout for CustomDialog

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#D3D7DB"
    android:orientation="vertical" >
    
    
    <TextView android:id="@+id/dialogtitle"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textColor="@android:color/black"
        android:text="Please enter the email address you used for the account"
        />

    <EditText
        android:id="@+id/emailedittext"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:ems="10"
        android:padding="5dp"
        android:cursorVisible="true"
        android:singleLine="true"
        android:background="@android:color/white"
        android:textColor="@android:color/black"
        android:hint="Enter Mail id"
        android:textSize="20dp" >

        <requestFocus />
    </EditText>
    
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:weightSum="2"
        android:orientation="horizontal">
        
         <Button 
            android:id="@+id/cancelbtn"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="CANCEL"/>
         
          <Button 
            android:id="@+id/okbtn"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Ok"/>
    </LinearLayout>

</LinearLayout>

Creating Dialog using the above layout

final Dialog dialog = new Dialog(MainActivity.this);
      // Include dialog.xml file
      dialog.setContentView(R.layout.forgotpassword);
      // Set dialog title
      dialog.setTitle("ALERT!!");

      // set values for custom dialog components - text, image and button
      Button okbtn = (Button) dialog.findViewById(R.id.okbtn);
      Button cancelbtn = (Button) dialog.findViewById(R.id.cancelbtn);
      final EditText emailedittext = (EditText) dialog.findViewById(R.id.emailedittext);

      dialog.show();
      dialog.getWindow().setSoftInputMode(
              WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

      // if decline button is clicked, close the custom dialog
      cancelbtn.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              // Close dialog
              dialog.dismiss();
          }
      });
      okbtn.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              String email=emailedittext.getText().toString();
              //do something more here
          }
      });

Final Code Now

MainActivity.java containing button showing alertdialog on clicking the button

//layout for MainActivity

activity_main.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" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">


    <Button
        android:id="@+id/simpledialog"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show Simple AlertDialog"/>
    <Button
        android:id="@+id/twobuttondialog"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show Two Button AlertDialog"
        android:layout_below="@+id/simpledialog"/>
    <Button
        android:id="@+id/threebuttondialog"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show Neutral Button AlertDialog"
        android:layout_below="@+id/twobuttondialog"/>
    <Button
        android:id="@+id/customdialog"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show Custom AlertDialog"
        android:layout_below="@+id/threebuttondialog"/>

</RelativeLayout>

//layout for custom Dialog

forgotpassword.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#D3D7DB"
  
    android:orientation="vertical" >
    
    
    <TextView android:id="@+id/dialogtitle"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textColor="@android:color/black"
        android:text="Please enter the email address you used for the account"
        />

    <EditText
        android:id="@+id/emailedittext"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:ems="10"
        android:padding="5dp"
        android:cursorVisible="true"
        android:singleLine="true"
        android:background="@android:color/white"
        android:textColor="@android:color/black"
        android:hint="Enter Mail id"
        android:textSize="20dp" >

        <requestFocus />
    </EditText>
    
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:weightSum="2"
        android:orientation="horizontal">
         
        <Button 
            android:id="@+id/cancelbtn"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="CANCEL"/>
         
          <Button 
            android:id="@+id/okbtn"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Submit"/>
    </LinearLayout>

</LinearLayout>

MainActivity.java

package com.coderzpassion.alertsample;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    Button simpledialog,twobuttondialog,threebuttondialog,customdialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        simpledialog=(Button)findViewById(R.id.simpledialog);
        //handling the click of simpledialog button
        simpledialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               showSimpleDialog();
            }
        });
        twobuttondialog=(Button)findViewById(R.id.twobuttondialog);
        twobuttondialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               showtwoButtonDialog();
            }
        });
        threebuttondialog=(Button)findViewById(R.id.threebuttondialog);
        //handling the click of threebuttondialog button
        threebuttondialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               showthreeButtonDialog();
            }
        });
        customdialog=(Button)findViewById(R.id.customdialog);
        //handling the click of customdialog button
        customdialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              showCustomDialog();
            }
        });
    }

    public void showSimpleDialog()
    {
        //create alertDialogBuilder
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);

        // set title
        alertDialogBuilder.setTitle("CoderzPassion");

        // set dialog message
        alertDialogBuilder
                .setMessage("Welcome To CoderzPassion!Keep Visting for Android Tutorials")
                .setCancelable(false)
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // if this button is clicked, do something here i am displaying Toast Message

                        Toast.makeText(MainActivity.this, "You clicked On Ok Button ", Toast.LENGTH_SHORT).show();
                    }
                });


        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();
    }
    public void showtwoButtonDialog()
    {
        //create alertDialogBuilder
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);

        // set title
        alertDialogBuilder.setTitle("Your Title");

        // set dialog message
        alertDialogBuilder
                .setMessage("Click yes to exit!")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // if this button is clicked,  do something here i am displaying Toast Message
                        Toast.makeText(MainActivity.this, "You clicked On Yes ", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // if this button is clicked, just close
                        // the dialog box and do nothing
                        dialog.cancel();
                    }
                });

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();
    }
    public void showthreeButtonDialog()
    {
        //create alertDialogBuilder
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);

        // set title
        alertDialogBuilder.setTitle("Your Title");

        // set dialog message
        alertDialogBuilder
                .setMessage("Click yes to exit!")
                .setCancelable(false)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // if this button is clicked,  do something here i am displaying Toast Message
                        Toast.makeText(MainActivity.this, "You clicked On Yes ", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //cancel the dialog box
                        dialog.cancel();
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // if this button is clicked,  do something here i am displaying Toast Message
                        Toast.makeText(MainActivity.this, "You clicked On No ", Toast.LENGTH_SHORT).show();

                    }
                });

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();
    }
    public void showCustomDialog()
    {
        final Dialog dialog = new Dialog(MainActivity.this);
        // Include dialog.xml file
        dialog.setContentView(R.layout.forgotpassword);
        // Set dialog title
        dialog.setTitle("ALERT!!");

        // set values for custom dialog components - text, image and button
        Button okbtn = (Button) dialog.findViewById(R.id.okbtn);
        Button cancelbtn = (Button) dialog.findViewById(R.id.cancelbtn);
        final EditText emailedittext = (EditText) dialog.findViewById(R.id.emailedittext);

        dialog.show();
        dialog.getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

        // if decline button is clicked, close the custom dialog
        cancelbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Close dialog
                dialog.dismiss();
            }
        });
        okbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email=emailedittext.getText().toString();
                //do something more here
            }
        });
    }

    @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;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Output

androidhowtoshowcustomdialogbox        androidworkingwithalertdialog           howtoalertdialoginandroid howtoshowalertdialoginandroid        howtoshowdialogbox