Create An AlertDialog Box in Android

In this tutorial, you will learn how to create an Alert Dialog box in your Android application. The use of the Alert Dialog box is to show an alert on your application to get the users attention or focus on something. The alert dialog box can manage up to three buttons, and a list of selectable items that can include checkboxes or radio buttons. So lets begin…

Create a new project in Eclipse File > New > Android Application Project. Fill in the details and name your project AlertDialogTutorial.

Application Name : AlertDialogTutorial

Project Name : AlertDialogTutorial

Package Name : com.androidbegin.alertdialogtutorial

Open your MainActivity.java and paste the following code.

MainActivity.java

package com.androidbegin.alertdialogtutorial;

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

public class MainActivity extends Activity {

	Button one_button, two_button, new_activity_button;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Get the view from alert_dialog.xml
		setContentView(R.layout.alert_dialog);

		// Locate the Buttons in alert_dialog.xml
		one_button = (Button) findViewById(R.id.one_button);
		two_button = (Button) findViewById(R.id.two_button);
		new_activity_button = (Button) findViewById(R.id.new_activity_button);

		// Capture first Button click
		one_button.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						MainActivity.this);

				// Set Alert Dialog Title
				builder.setTitle("Alert Dialog Tutorial");

				// Set an Icon for this Alert Dialog
				builder.setIcon(R.drawable.androidhappy);

				// Set Alert Dialog Message
				builder.setMessage(
						"An AlertDialog Tutorial from AndroidBegin.com")

				// Neautral button functionality
						.setNeutralButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int arg0) {
										Toast.makeText(
												MainActivity.this,
												"You clicked on OK",
												Toast.LENGTH_SHORT).show();
										// Do more stuffs
									}
								});

				// Create the Alert Dialog
				AlertDialog alertdialog = builder.create();

				// Show Alert Dialog
				alertdialog.show();
			}
		});

		// Capture second Button click
		two_button.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						MainActivity.this);

				// Set Alert Dialog Title
				builder.setTitle("Alert Dialog Tutorial");

				// Set an Icon for this Alert Dialog
				builder.setIcon(R.drawable.androidhappy);

				// Set Alert Dialog Message
				builder.setMessage("Do you want to exit?")

						// Positive button functionality
						.setPositiveButton("Yes",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int arg0) {
										Toast.makeText(
												MainActivity.this,
												"You clicked on Yes",
												Toast.LENGTH_SHORT).show();
										// Do more stuffs
										// finish();
									}
								})
						// Negative button functionality
						.setNegativeButton("No",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int arg0) {
										Toast.makeText(
												MainActivity.this,
												"You clicked on No",
												Toast.LENGTH_SHORT).show();
										// Do more stuffs
										// dialog.cancel();
									}
								});

				// Create the Alert Dialog
				AlertDialog alertdialog = builder.create();

				// Show Alert Dialog
				alertdialog.show();
			}
		});

		// Capture third Button click
		new_activity_button.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						MainActivity.this);

				// Set Alert Dialog Title
				builder.setTitle("Alert Dialog Tutorial");

				// Set an Icon for this Alert Dialog
				builder.setIcon(R.drawable.androidhappy);

				// Set Alert Dialog Message
				builder.setMessage("Do you want to open a new Activity?")

						// Positive button functionality
						.setPositiveButton("Yes",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int arg0) {
										Toast.makeText(
												MainActivity.this,
												"You clicked on Yes",
												Toast.LENGTH_SHORT).show();
										Intent i = new Intent(
												MainActivity.this,
												NewActivity.class);
										startActivity(i);
									}
								})
						// Negative button functionality
						.setNegativeButton("No",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int arg0) {
										Toast.makeText(
												MainActivity.this,
												"You clicked on No",
												Toast.LENGTH_SHORT).show();
										dialog.cancel();
										// Do more stuffs
									}
								});

				// Create the Alert Dialog
				AlertDialog alertdialog = builder.create();

				// Show Alert Dialog
				alertdialog.show();
			}
		});
	}

}

We have created three buttons with the codes above. The first button shows an Alert Dialog with a single Ok button by using the code below.

// Capture first Button click
        one_button.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
            	AlertDialog.Builder builder = new AlertDialog.Builder(AlertDialogActivity.this);

            	// Set Alert Dialog Title
            	builder.setTitle("Alert Dialog Tutorial");

            	// Set an Icon for this Alert Dialog
            	builder.setIcon(R.drawable.androidhappy);

            	// Set Alert Dialog Message
            	builder.setMessage("An AlertDialog Tutorial from AndroidBegin.com")

            		   	// Neautral button functionality 
     		           .setNeutralButton("OK", new DialogInterface.OnClickListener() {
     		               public void onClick(DialogInterface dialog, int arg0) {
     		            	  Toast.makeText(AlertDialogActivity.this, "You clicked on OK", Toast.LENGTH_SHORT).show();    		            	   
     		            	  //Do more stuffs
     		               }
     		           });

            	// Create the Alert Dialog
     		    AlertDialog alertdialog = builder.create();

     		    // Show Alert Dialog
     		    alertdialog.show();
     		}  
        });

Output :

Alert  Dialog One Button

Second button shows an Alert Dialog with a Yes/No button using the code below. On Yes button click you can exit the app by using finish();

// Capture second Button click
        two_button.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
            	AlertDialog.Builder builder = new AlertDialog.Builder(AlertDialogActivity.this);

            	// Set Alert Dialog Title
            	builder.setTitle("Alert Dialog Tutorial");

            	// Set an Icon for this Alert Dialog
            	builder.setIcon(R.drawable.androidhappy);

            	// Set Alert Dialog Message
            	builder.setMessage("Do you want to exit?")

            		   	// Positive button functionality 
     		           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
     		               public void onClick(DialogInterface dialog, int arg0) {
     		            	 Toast.makeText(AlertDialogActivity.this, "You clicked on Yes", Toast.LENGTH_SHORT).show();    		            	   
     		            	 //Do more stuffs
     		            	 //finish();
     		               }
     		           })
     		           	// Negative button functionality 
     		           .setNegativeButton("No", new DialogInterface.OnClickListener() {
     		               public void onClick(DialogInterface dialog, int arg0) {
     		            	 Toast.makeText(AlertDialogActivity.this, "You clicked on No", Toast.LENGTH_SHORT).show();
     		            	 //Do more stuffs
     		            	 //dialog.cancel();
     		               }
     		           });

            	// Create the Alert Dialog
     		    AlertDialog alertdialog = builder.create();

     		    // Show Alert Dialog
     		    alertdialog.show();
     		}  
        });

Output :

Alert  Dialog Two Buttons

Third button shows an Alert Dialog with a Yes/No button using the code below. On Yes button click will open a new activity using an intent.

// Capture third Button click
        new_activity_button.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
            	AlertDialog.Builder builder = new AlertDialog.Builder(AlertDialogActivity.this);

            	// Set Alert Dialog Title
            	builder.setTitle("Alert Dialog Tutorial");

            	// Set an Icon for this Alert Dialog
            	builder.setIcon(R.drawable.androidhappy);

            	// Set Alert Dialog Message
            	builder.setMessage("Do you want to open a new Activity?")

            		   	// Positive button functionality 
     		           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
     		               public void onClick(DialogInterface dialog, int arg0) {
     		            	  Toast.makeText(AlertDialogActivity.this, "You clicked on Yes", Toast.LENGTH_SHORT).show();    		            	   
     		            	  Intent i = new Intent(AlertDialogActivity.this, NewActivity.class);
     		            	  startActivity(i); 
     		               }
     		           })
     		           	// Negative button functionality 
     		           .setNegativeButton("No", new DialogInterface.OnClickListener() {
     		               public void onClick(DialogInterface dialog, int arg0) {
     		            	  Toast.makeText(AlertDialogActivity.this, "You clicked on No", Toast.LENGTH_SHORT).show();
     		            	  dialog.cancel();
     		            	  //Do more stuffs
     		               }
     		           });

            	// Create the Alert Dialog
     		    AlertDialog alertdialog = builder.create();

     		    // Show Alert Dialog
     		    alertdialog.show();
     		}  
        });

Output :

New Activity Button

We have prepared a sample alert dialog icon for this tutorial. Insert your downloaded sample alert dialog icon into your res > drawable-hdpi.

Sample Alert Dialog Icon

[wpfilebase tag=file id=27 tpl=download-button /]

Next, create an XML file for your MainActivity Graphical Layout. Go to res > layout > Right Click on layout > New > Android XML File

Name your new XML file alert_dialog.xml and paste the following code.

alert_dialog.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" >

    <Button
        android:id="@+id/one_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/two_button"
        android:layout_centerHorizontal="true"
        android:text="@string/one_button" />

    <Button
        android:id="@+id/two_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/new_activity_button"
        android:layout_centerHorizontal="true"
        android:text="@string/two_button" />

    <Button
        android:id="@+id/new_activity_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/new_activity_button" />

</RelativeLayout>

Next, create a new activity in a new class called NewActivity.java. Go to File > New > Class and name it NewActivity.java. Select your package named com.androidbegin.alertdialogtutorial and click Finish.

Open your NewActivity.java and paste the following code.

NewActivity.java

package com.androidbegin.alertdialogtutorial;

import android.os.Bundle;
import android.app.Activity;

public class NewActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Get the view from new_activity.xml
		setContentView(R.layout.new_activity);
	}
}

Next, create an XML graphical layout for your NewActivity. Go to res > layout > Right Click on layout > New > Android XML File

Name your new XML file new_activity.xml and paste the following code.

new_activity.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" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:text="@string/NewActivity"/>

</RelativeLayout>

Next, change the application name and texts. Open your strings.xml in your res > values folder and paste the following code.

strings.xml

<resources>

    <string name="app_name">AlertDialog Tutorial</string>
    <string name="menu_settings">Settings</string>
    <string name="NewActivity">I have successfully created an Alert Dialog in Android that opens a new activity on positive "Yes" button click.</string>
    <string name="one_button">Alert Dialog With One Button</string>
    <string name="two_button">Alert Dialog With Two Button</string>
    <string name="new_activity_button">Alert Dialog Open New Activity</string>

</resources>

In your AndroidManifest.xml, we need to declare an activity. Open your AndroidManifest.xml and paste the following code.

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidbegin.alertdialogtutorial"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".NewActivity" >
        </activity>
    </application>

</manifest>

Output:

AlertDialog Tutorial ScreenShots

Source Code 

[purchase_link id=”7837″ text=”Purchase to Download Source Code” style=”button” color=”green”]