RSS

Android AlertDialog

25 Jul

Hey guys, today we gonna look at AlertDialogs. AlertDialogs are used when you want to inform the user of something urgent. There are different types of dialogs which we’ll see as we go on. That’s pretty much it for the theory. Lets look at the implemenation.

In this example, I’ll show how to alert the user when he presses an exit button prompting him if he really wants to exit. You’ve seen this type of dialog a gazilion times im sure of it.

First off we build the alert.

AlertDialog alert = new AlertDialog.Builder(Camera.this).create();

AlertDialog.builder(Context) takes in a context as an argument. In this case the class is Camera and its context will be Camera.this.

alert.setMessage("Are you sure you want to exit?");

setMessage() method will display the message in the alert.

alert.setButton("Yes", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					Camera.this.finish();
				}
			});

setButton() takes in a string and a listener as its arguments. The string is the text that will display on the button. The listener is what adds the functionality to the button. In this case if the user clicks on this button it should end the app.

Finally we have to display the alert.

alert.show();

There are other methods like the setTitle() which sets the title.
It should look like this:

Here is the full code snippet:

AlertDialog alert = new AlertDialog.Builder(Camera.this).create();
			alert.setMessage("Are you sure you want to exit?");
			alert.setButton("Yes", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					Camera.this.finish();
				}
			});
                       alert.setButton2("No", new DialogInterface.OnClickListener(){
				public void onClick(DialogInterface dialog, int which){
					dialog.cancel();
				}
				
			});
			alert.show();
Advertisements
 
Leave a comment

Posted by on July 25, 2012 in Uncategorized

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: