Creating alert dialog is very easy. In this tutorial i will be discussing about creating different alert dialogues with one button(ok button), two buttons(yes or no buttons) and three buttons(yes, no and cancel buttons).

Download Code

Android alert dialog with One button

The following code will create a simple alert dialog with one button. In the following code setTitle() method is used for set Title to alert dialog. setMessage() is used for setting message to alert dialog. setIcon() is to set icon to alert dialog.

AlertDialog alertDialog = new AlertDialog.Builder(
						AlertDialogActivity.this).create();

		// Setting Dialog Title
		alertDialog.setTitle("Alert Dialog");

		// Setting Dialog Message
		alertDialog.setMessage("Welcome to AndroidHive.info");

		// Setting Icon to Dialog
		alertDialog.setIcon(R.drawable.tick);

		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
				// Write your code here to execute after dialog closed
				Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
				}
		});

		// Showing Alert Message
		alertDialog.show();

This output of about code will be like following image.

Alert Dialog with One button

Android alert dialog with two button

The following code will create alert dialog with two button. setPositiveButton() is used to create a positive button in alert dialog and setNegativeButton() is used to invoke negative button to alert dialog.

AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertDialogActivity.this);

		// Setting Dialog Title
		alertDialog.setTitle("Confirm Delete...");

		// Setting Dialog Message
		alertDialog.setMessage("Are you sure you want delete this?");

		// Setting Icon to Dialog
		alertDialog.setIcon(R.drawable.delete);

		// Setting Positive "Yes" Button
		alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,int which) {

			// Write your code here to invoke YES event
			Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();
			}
		});

		// Setting Negative "NO" Button
		alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,	int which) {
			// Write your code here to invoke NO event
			Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
			dialog.cancel();
			}
		});

		// Showing Alert Message
		alertDialog.show();

This output of about code will be like following image.

Alert Dialog with two buttons

Android alert dialog with three button

Here setNeutralButton() is used to create a neutral cancel button

AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertDialogActivity.this);

				// Setting Dialog Title
				alertDialog.setTitle("Save File...");

				// Setting Dialog Message
				alertDialog.setMessage("Do you want to save this file?");

				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.save);

				// Setting Positive "Yes" Button
				alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					// User pressed YES button. Write Logic Here
					Toast.makeText(getApplicationContext(), "You clicked on YES",
										Toast.LENGTH_SHORT).show();
					}
				});

				// Setting Negative "NO" Button
				alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					// User pressed No button. Write Logic Here
					Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
					}
				});

				// Setting Netural "Cancel" Button
				alertDialog.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					// User pressed Cancel button. Write Logic Here
					Toast.makeText(getApplicationContext(), "You clicked on Cancel",
										Toast.LENGTH_SHORT).show();
					}
				});

				// Showing Alert Message
				alertDialog.show();

This output of about code will be like following image.

Android alert dialog with three buttons
Subscribe
Notify of
guest
87 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
sidharth
sidharth
9 years ago

clear n simple.. cool 🙂

srbkrishnan
srbkrishnan
9 years ago

Will Alert Dialog work inside a class Implementing BroadcastListener??

Anish Bharatha
Anish Bharatha
9 years ago

is there any way to know if this message is being shown ?
For Dialog class, isShowing() method returns true if the alert is shown to user.
any clue ?

Sagar Vadaria90
Sagar Vadaria90
9 years ago

unable add window

Donna R.
Donna R.
9 years ago

I get 3 buttons:
“Choice A”, “Choice B”, “Cancel”, in Gingerbread.
But in Jelly Bean I get it backwards: “Cancel”, “Choice B”, “Choice A”.

How do I fix that?

PolskaGórą
PolskaGórą
6 years ago
Reply to  Donna R.

Replace their names in code together with runnables 😉

minhdangtran
minhdangtran
9 years ago

thanks you very much!

Marci
Marci
8 years ago

Thank you very much! It’s working and it’s very simple… cool 🙂

Irfan khan
Irfan khan
8 years ago

cool brother great work

Roney
Roney
8 years ago

To learn ANDROID from the very beginning

VISIT ANDROIDITUTS

http://www.androidituts.com

Sonjay Singh
Sonjay Singh
8 years ago
Reply to  Roney

Bookmark Added
Done !!

ashish
ashish
8 years ago

awesome explantion

sanjay
sanjay
8 years ago

very very help full tutorial…………

sanjay
sanjay
8 years ago
vignesh
vignesh
7 years ago
Reply to  sanjay

How to change the theme of the alert dialog and adding image for button ?

Reza yuriputra
8 years ago

very useful 😀 GBU admin nice 😀

GOH CHONG LOONG
GOH CHONG LOONG
8 years ago

Bravo!!Ur tutorial gives the right solution!!!

Marvin
Marvin
8 years ago

thank you so much.

anonymous
anonymous
8 years ago

motherfuking article
this aint executing u fucker atleast give some more details u asshole.

qqqq
qqqq
8 years ago
Reply to  anonymous

what resource type will be use? this dude is right, give more details for every article

dfdsf
dfdsf
6 years ago
Reply to  anonymous

Haram jarea, nikal ja

Meghna
Meghna
8 years ago

Thanks for the clean explanation Ravi.. Even this http://www.compiletimeerror.com/2013/08/android-alert-dialog-example.html might be helpful, have a look…

Erhan Cetin
Erhan Cetin
8 years ago

Take a look here , this is my solution for it with source code:

http://www.erhancetin.com.tr/2013/10/how-to-display-alert-dialog-in-android.html

studenttt
studenttt
8 years ago

Hi how do i start the NetAsync when pressed on positve button?

I tried putting NetAsync(view); put theres error “Cannot refer to a non-final variable view inside an inner class defined in a different method”

george
george
7 years ago

Hello. I need someone
to develop a simple app. will use java , php and sql. please reply to [email protected]
if you can help me. I will share the
credits :). Thanks

hari
hari
7 years ago

i need to know how to do chat application

Dharmik
Dharmik
7 years ago

You really did a great job. 🙂

prajwal shetty
prajwal shetty
7 years ago

Its working, thanks dude:)

Paqco Suarex
Paqco Suarex
7 years ago

That is exactly what I was looking for, Thank you!!!

Clemar
Clemar
7 years ago

Problem solved!!, Thanks!!

bteranv2
bteranv2
7 years ago

Thank, It is very useful.

itechaleart
7 years ago

Thank it useful but provide .zip file of code

Mayank Sood
Mayank Sood
6 years ago

my app crashes every time. any solution?

Daniel Baumert (HackerOnBoard)
Daniel Baumert (HackerOnBoard)
6 years ago
Reply to  Mayank Sood

Use this import import android.support.v7.app.AlertDialog; and
Builder(this); not Builder(getApplicationContext());

Mayank Sood
Mayank Sood
6 years ago

app crashes, any solution?

this is my code

package com.techcuriosity.vcn;

import com.techcuriosity.vcn.library.UserFunctions;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
/*import android.view.Menu; */

public class LoginActivity extends Activity {

TextView registerlink;
Button loginBtn;
EditText etUsername;
EditText etPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
//Toast.makeText(getApplicationContext(), “Invalid Email”, Toast.LENGTH_SHORT).show();
registerlink = (TextView) findViewById(R.id.link_to_register);
registerlink.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(),RegisterActivity.class);
startActivity(i);
finish();
}
});
loginBtn = (Button) findViewById(R.id.btnLogin);
etUsername = (EditText) findViewById(R.id.etUserName);
etPassword = (EditText) findViewById(R.id.etPassword);
loginBtn.setOnClickListener(new View.OnClickListener() {

@SuppressWarnings(“deprecation”)
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
AlertDialog.Builder builder = new AlertDialog.Builder(
LoginActivity.this);
builder.setTitle(“Sample Alert”);
builder.setMessage(“Sample One Action Button Alert”);
builder.setPositiveButton(“OK”,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Log.e(“info”, “OK”);
}
});
builder.show();
//UserFunctions userFunction = new UserFunctions();
}
});
}

/*@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
*/

}

suresh reddy
suresh reddy
6 years ago

I have listview in my app when i am click on any one item in that listview how to get the alertdialog box send me any reference

Karan Kumar Joura
6 years ago

Really It is good example. But when i use setPositiveButton or setNegativeButton. It causes error.

sanjeev
sanjeev
6 years ago

Really good example.but how to use setpositive and negative bottom from layout.that means own customized buttom.

ashwini
ashwini
6 years ago

how to fetch username from database and display it into alertDialog

Dragan Cakardic
Dragan Cakardic
6 years ago
Reply to  ashwini

query database for name and assing name to textview in alertdialog.

http://stackoverflow.com/questions/13341560/how-to-create-a-custom-dialog-box-in-android

Millah
Millah
6 years ago

thank you ravi… this tutorial very helpful

Ravi Tamada
6 years ago
Reply to  Millah

You are welcome.

john
john
5 years ago

hey…. i am try to create a automatic login frames for android an ios.. can u help me please…

Samar Hasan
Samar Hasan
5 years ago

How could we view an image and txt in the dialog without buttons 🙂

Ravi Tamada
5 years ago
Reply to  Samar Hasan

Use Dialog Fragment.

Samar Hasan
Samar Hasan
5 years ago
Reply to  Ravi Tamada

thank’s 🙂 but i try to put the code onitemclick of custom grid view but nothing appeared when click the item

daivaprasad
daivaprasad
5 years ago
Reply to  Ravi Tamada

I have 2 Buttons in Popup window…
How can I display Dialog box when i click on button from the Popupwindow ?

Anu_143#
Anu_143#
5 years ago

Hi… I have been trying to edit some of the strings in my apk file,
since I want to add some modified info in the app. But I am not able to
edit them. Even if I make changes in strings.xml, there are certain
errors that do not recompile my file. What am I suppose to do? it’s my
project work and no one could help me around, please tell me how to edit
these strings??

chandan kumar
chandan kumar
5 years ago

how can i seticon through drawable please reply fast anybody guyzz

honest hearts
honest hearts
5 years ago

You are like my sifu. Give all the information that I need. Thanks.

أنا أحب يسوع
أنا أحب يسوع
4 years ago

how to show alertdialog on navigation drawer when click the item menu?(logout menu)
with positive and negative button

أنا أحب يسوع
أنا أحب يسوع
4 years ago

problem solve……………….

@SuppressWarnings(“StatementWithEmptyBody”)
@Override
public boolean onNavigationItemSelected(MenuItem item) {
FragmentManager fm = getFragmentManager();
AlertDialog alertDialog;
int id = item.getItemId();

if (id == R.id.Your_NAV_ID1) {

alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle(“YOUR TITLE”);
alertDialog.setIcon(R.drawable.YOUR_IMAGE_TITLE);
alertDialog.setMessage(Html.fromHtml(“YOUR MESSAGEYOUR MESSAGE”));
alertDialog.setButton(Dialog.BUTTON_POSITIVE,”YOUR STRING BUTTON”,new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialogInterface, int which) {
Toast.makeText(getApplicationContext(), “YOUR TOAST”, Toast.LENGTH_SHORT).show();
//////////////
}

} );
alertDialog.setButton(Dialog.BUTTON_NEGATIVE,”OUR STRING BUTTON”,new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialogInterface, int which) {
Toast.makeText(getApplicationContext(), “YOUR TOAST”, Toast.LENGTH_SHORT).show();
dialogInterface.cancel();
}

} );

alertDialog.show();
/////////CHANGE BUTTON FONT AND COLOR alertDialog.getButton(alertDialog.BUTTON_NEGATIVE).setTextColor(Color.parseColor(“#ffffff”));
alertDialog.getButton(alertDialog.BUTTON_NEGATIVE).setBackgroundColor(Color.parseColor(“#000000”));
alertDialog.getButton(alertDialog.BUTTON_POSITIVE).setTextColor(Color.parseColor(“#ffffff”));
alertDialog.getButton(alertDialog.BUTTON_POSITIVE).setBackgroundColor(Color.parseColor(“#ff9600”));

} else if (id == R.id.Your_NAV_ID2) {
fm.beginTransaction().replace(R.id.content_frame, new YOUR_CLASS()).commit();

}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}

Mesfun
Mesfun
4 years ago

Thank very much i learn a lot from your Blog
i create a listview inside alertbox an app i can not figure out how to choose items this is my file link is

https://www.dropbox.com/sh/kbkgl5a10lz2kzf/AADwVn6CC4PRdjSz76l2DkYva?dl=0

what i want is when you select Atlanta show a dialog box and choose red yellow and the same choose Texas and dialog choose yellow Brown

click a button USA states Grow Flower and show only The following were selected Atlanta Texas

but i want when i click

a button to show me

The following were selected Atlanta red,yellow Texas yellow,Brown

incase if u figure out please email answer at [email protected]

Error Eliminator
Error Eliminator
4 years ago

Nice simple way to explain difficult things…..

Ravi Tamada
4 years ago

Thank you

Julius Ndyakalika
Julius Ndyakalika
4 years ago

thanks

girish singh
girish singh
4 years ago

comment image

how to create dialog like this anyone help me advance thanks…

Ravi Tamada
4 years ago
Reply to  girish singh

Use DialogFragment

girish singh
girish singh
4 years ago
Reply to  Ravi Tamada

Thanks

Mangesh Panchwagh
Mangesh Panchwagh
3 years ago

from where do i get R.drawable.delete

Mitesh Makwana
Mitesh Makwana
3 years ago

any example of set alarm using date picker and time picker?

Mustafa Shaikh
Mustafa Shaikh
3 years ago

i want to set password in Alert Dialog box and open next Activity if the password match else don’t match…????
how to set in database???

Vanaja Menon
Vanaja Menon
3 years ago

How can we place image in alertbox,which taken from database

rogergcc
rogergcc
3 years ago

ok thks

Laxmi
Laxmi
2 years ago

How to change background color of alert box

87
0
Would love your thoughts, please comment.x
()
x