In this tutorial, we show you how to display an alert box in Android. See flowing Steps :

  1. First, use the AlertDialog.Builder to create the alert box interface, like title, message to display, buttons, and button onclick function
  2. Later attach above builder to AlertDialog and display it.
  3. Done.

P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

1 Android Layout Files

Simpel layout file, display a button on screen.

File : res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" >
        android:text="Show Alert Box" />

2. Activity

When user click on this button, display the alert box, with your pre-defined alert dialog interface.

File :

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
	final Context context = this;
	private Button button;
	public void onCreate(Bundle savedInstanceState) {
		button = (Button) findViewById(;
		// add button listener
		button.setOnClickListener(new OnClickListener() {
		public void onClick(View arg0) {
			AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
			// set title
			alertDialogBuilder.setTitle("Your Title");
			// set dialog message
				.setMessage("Click yes to exit!")
				.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						// if this button is clicked, close
						// current activity
				.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
				// create alert dialog
				AlertDialog alertDialog = alertDialogBuilder.create();
				// show it;

3. Demo

Start it, display a button.

android alert box example

When button is clicked, display the alert box

android alert box example

If “Yes” button is clicked, close the activity and return back to your Android main screen.

android alert box example

Download Source Code

Download it – (16 KB)


  1. Android AlertDialog Javadoc
  2. Android Dialog example
Tags :
Founder of and, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Related Posts

Popular Posts