Android | Alert Dialog Box and How to create it - GeeksforGeeks

01 Feb, 2019
Alert Dialog shows the Alert message and gives the answer in the form of yes or no. Alert Dialog displays the message to warn you and then according to your response the next step is processed.
Android Alert Dialog is built with the use of three fields: Title, Message area, Action Button.Alert Dialog code has three methods:
setTitle() method for displaying the Alert Dialog box Title
setMessage() method for displaying the message
setIcon() method is use to set the icon on Alert dialog box.
Then we add the two Button, setPositiveButton and setNegativeButton to our Alert Dialog Box as shown below.
Example:
Below are the steps for Creating the Alert Dialog Android Application:
Step 1: Create a new project. After that, you have java and XML file.
Step 2: Open your XML file and then add TextView for message as shown below (you can change it accordingly).
Step 3: Now, open up the activity java file. After, on create method declaration, the onbackpressed method is called when you click the back button of your device.
Step 4: Create the object of Builder class Using AlertDialog.Builder. Now, set the Title, message.
Step 5: In a builder object set the positive Button now gives the button name and add the OnClickListener of DialogInterface. Same as with the negative Button, at last, create the Alert dialog Box with builder object and then show the Alert Dialog.
Step 6: Now if positive button press finish the app goto outside from the app if negative then finish the dialog box
Step 7: Now run it and then press the back button. After that click Yes or No Button.The complete code of MainActivity.java or activity_main.xml of Alert Dialog is given below:activity_main.xmlMainActivity.javaactivity_main.xml<?xml version="1.0" encoding="utf-8"?><RelativeLayout     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"    tools:context=".MainActivity">  <TextView    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="Press The Back Button of Your Phone."    android:textStyle="bold"    android:textSize="30dp"    android:gravity="center_horizontal"    android:layout_marginTop="180dp"    />  </RelativeLayout>MainActivity.javapackage org.geeksforgeeks.navedmalik.alertdialog;  import android.content.DialogInterface;import android.support.v7.app.AlertDialog;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;  public class MainActivity extends AppCompatActivity {      @Override    protected void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }      // Declare the onBackPressed method    // when the back button is pressed    // this method will call    @Override    public void onBackPressed()    {          // Create the object of        // AlertDialog Builder class        AlertDialog.Builder builder            = new AlertDialog                  .Builder(MainActivity.this);          // Set the message show for the Alert time        builder.setMessage("Do you want to exit ?");          // Set Alert Title        builder.setTitle("Alert !");          // Set Cancelable false        // for when the user clicks on the outside        // the Dialog Box then it will remain show        builder.setCancelable(false);          // Set the positive button with yes name        // OnClickListener method is use of        // DialogInterface interface.          builder            .setPositiveButton(                "Yes",                new DialogInterface                    .OnClickListener() {                          @Override                        public void onClick(DialogInterface dialog,                                            int which)                        {                              // When the user click yes button                            // then app will close                            finish();                        }                    });          // Set the Negative button with No name        // OnClickListener method is use        // of DialogInterface interface.        builder            .setNegativeButton(                "No",                new DialogInterface                    .OnClickListener() {                          @Override                        public void onClick(DialogInterface dialog,                                            int which)                        {                              // If user click no                            // then dialog box is canceled.                            dialog.cancel();                        }                    });          // Create the Alert dialog        AlertDialog alertDialog = builder.create();          // Show the Alert Dialog box        alertDialog.show();    }}Output:Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!My Personal Notes
arrow_drop_upSave
The complete code of MainActivity.java or activity_main.xml of Alert Dialog is given below:
activity_main.xml
MainActivity.java
<?xml version="1.0" encoding="utf-8"?><RelativeLayout     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"    tools:context=".MainActivity">  <TextView    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="Press The Back Button of Your Phone."    android:textStyle="bold"    android:textSize="30dp"    android:gravity="center_horizontal"    android:layout_marginTop="180dp"    />  </RelativeLayout>
package org.geeksforgeeks.navedmalik.alertdialog;  import android.content.DialogInterface;import android.support.v7.app.AlertDialog;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;  public class MainActivity extends AppCompatActivity {      @Override    protected void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }      // Declare the onBackPressed method    // when the back button is pressed    // this method will call    @Override    public void onBackPressed()    {          // Create the object of        // AlertDialog Builder class        AlertDialog.Builder builder            = new AlertDialog                  .Builder(MainActivity.this);          // Set the message show for the Alert time        builder.setMessage("Do you want to exit ?");          // Set Alert Title        builder.setTitle("Alert !");          // Set Cancelable false        // for when the user clicks on the outside        // the Dialog Box then it will remain show        builder.setCancelable(false);          // Set the positive button with yes name        // OnClickListener method is use of        // DialogInterface interface.          builder            .setPositiveButton(                "Yes",                new DialogInterface                    .OnClickListener() {                          @Override                        public void onClick(DialogInterface dialog,                                            int which)                        {                              // When the user click yes button                            // then app will close                            finish();                        }                    });          // Set the Negative button with No name        // OnClickListener method is use        // of DialogInterface interface.        builder            .setNegativeButton(                "No",                new DialogInterface                    .OnClickListener() {                          @Override                        public void onClick(DialogInterface dialog,                                            int which)                        {                              // If user click no                            // then dialog box is canceled.                            dialog.cancel();                        }                    });          // Create the Alert dialog        AlertDialog alertDialog = builder.create();          // Show the Alert Dialog box        alertDialog.show();    }}
vartika02
android
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Collections in Java
Set in Java
Overriding in Java