Anda di halaman 1dari 10

AlertDialog box in Android

AlertDialog box and how to deal with those dialogs. Dialog is a small window which takes a
small part in your screen. It is majorly used to react to user driven events. Dialogs are always
part of your activity. It gets the focus unless the user closes it. Android dialogs are used for many
purposes such as,

1. to inform the user about a problem that has occurred.


2. to give message to the user about an ongoing process.
3. to confirm before deleting/saving data.

Dialog class is the base class for all dialog types. The
subclasses of Dialog class are,

1. AlertDialog
2. Progress Dialog
3. DatePickerDialog
4. TimePickerDialog

We should create the instance of one of the above subclasses to create a dialog.

Structure of a Dialog
A simple android dialog box has the following components.

 Title
o This component is optional. You can omit it if your content area has a simple
message that needs to be shown to the user as below.If your content area is
designed to ask user confirmation or if it needs any user input then it is a good
practice to add a title.

 Content area
o This component can contain,
 A message
 A list
 Custom layout

 Action buttons
o This component is used to collect user response(Example “OK”, “Cancel” etc
buttons). There can be maximum three action buttons.

Let us now see how we can create a simple AlertDialog box in android:

Step 1: Set up the android environment


Please go through the article on Environment to know how to set up an android working
environment.

Step 2 : Create an android project


Create a project named “My_Dialog” with the activity “Dialog”.

Step 3: Create a layout


When you create your project, the layout main.xml gets created automatically. Here in this
example we are going to use this main.xml to create an alertDialog box.

Open main.xml and paste the below code.

1 <?xml version="1.0" encoding="utf-8"?>


2 <RelativeLayout android:id="@+id/RelativeLayout01"
3 android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="<a
4 href="http://schemas.android.com/apk/res/android">http://schemas.android.com
/apk/res/android</a>">
5 <EditText android:id="@+id/EditText01" android:text="AlertDialog Demo"
6 android:layout_height="50dip" android:layout_width="180dip"></EditText>
7 <Button android:id="@+id/Button01" android:layout_width="wrap_content"
8 android:layout_height="wrap_content" android:layout_below="@+id/EditText01"
9 android:text="Clear Data"></Button>
10 </RelativeLayout>

Our main.xml contains a relative layout which in turn contains an Edittext which has a default
text “AlertDialod Demo” and a button named “Clear data”.
Step 4: Create the Activities
package my.app;
2 import android.app.Activity;
3 import android.app.AlertDialog;
4 import android.content.DialogInterface;
5 import android.content.Intent;
6 import android.os.Bundle;
7 import android.view.View;
8 import android.view.View.OnClickListener;
9 import android.widget.Button;
10 import android.widget.EditText;
11 import android.widget.TextView;
12 import android.widget.Toast;
13
14 public class Dialog extends Activity {
15 Button Clear;
16 EditText edit_data;
17 /** Called when the activity is first created. */
18 @Override
19 public void onCreate(Bundle savedInstanceState) {
20 super.onCreate(savedInstanceState);
21 setContentView(R.layout.main);
22
23 Clear=(Button)findViewById(R.id.Button01);
24 edit_data=(EditText)findViewById(R.id.EditText01);
25
26 Clear.setOnClickListener(new OnClickListener() {
27 @Override
28 public void onClick(View v) {
29 // TODO Auto-generated method stub
30 AlertDialog.Builder builder=new AlertDialog.Builder(Dialog.this);
31 //Set a title
32 builder.setTitle("Confirm");
33 //Set a message
34 builder.setMessage("Do you want to Clear?");
35
36 builder.setPositiveButton("OK",new DialogInterface.OnClickListener() {
37
38 @Override
39 public void onClick(DialogInterface dialog, int which) {
40 // TODO Auto-generated method stub
41
42 //clearing the contents of edittext on click of OK button
43 edit_data.setText("");
44 //Displaying a toast message
Toast.makeText(getApplicationContext(), "Your text has been cleared",
45
Toast.LENGTH_LONG).show();
46
47 }
48 });
49 builder.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
50
51 @Override
52 public void onClick(DialogInterface dialog, int which) {
53 // TODO Auto-generated method stub
54 dialog.cancel();
55 }
56 });
57
58 //Create the dialog
59 AlertDialog alertdialog=builder.create();
60
61 //show the alertdialog
62 alertdialog.show();
63
64 }
65 });
66 }
67 }

As you can see in the above code the dialog is created using following steps:

1. AlertDialog.Builder is used to override the defalut layout(setting the message,title etc.)


2. Set the title and message to the AlertDialog box.
3. Set up the action Buttons and their respective functionalities.
4. Create the dialog box by calling builder.create().
5. Displaying the dialog box using show() method.
6. Step 5: Declare the Activities in AndroidManifest.xml
7. Your launcher Activity is automatically registered. If you want to know more information
about AndroidMannifest.xml, please refer our earlier article on manifest. The code of the
AndroidManifest.xml is as below.
1 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="<a
2 href="http://schemas.android.com/apk/res/android">http://schemas.android.com
/apk/res/android</a>"
3 package="my.app"
4 android:versionCode="1"
5 android:versionName="1.0">
6 <application android:icon="@drawable/icon" android:label="@string/app_name">
7 <activity android:name=".Android_Toast"
8 android:label="@string/app_name">
9 <intent-filter>
10 <action android:name="android.intent.action.MAIN" />
11 <category android:name="android.intent.category.LAUNCHER" />
12 </intent-filter>
13 </activity>
14 </application>
15 <uses-sdk android:minSdkVersion="8" />
16 </manifest>

15. Step 6: Run your Application


16. Select the project “My_Dialog”-> Run As-> Android Application. Now your activity
“Dialog” fires up like below.
17.
18. Click on the Button “Clear Data” which opens up an alertdialog box like below.
19.
20. As you can see in the above image the AlertDialog box is asking the confirmation
whether to clear the text in the Edittext or not. Clicking “OK” button clears your EditText
data. Cancel action button simply closes AlertDialog box without clearing the text. I have
set a toast message when the user clicks on “OK” saying that the data is cleared(Whereas
creating a toast for this App is optional). For more information about Toast message,
please refer the post toast. The Edittext data is cleared and a toast is displayed as below.
21. As we said earlier an alertdialog box can be created without the title, without the action
buttons and without the icon. The following are the variants of an alertdialog box.

Alertdialog box without title


To create an AlertDialog box without title comment or delete the below line in your
Dialog.java file.

1 builder.setTitle("Confirm");

The output without title is as below.


Till now we have seen AlertDialog box with two buttons. We can also create dialogs having
3 buttons or Dialogs with one buttons.

AlertDialog with one buttons


Comment or delete the below code snippet from your Dialog.java file. and run your
application.

builder.setNegativeButton("Cancel",new
1
DialogInterface.OnClickListener()
2 {
3 @Override
4 public void onClick(DialogInterface dialog, int which)
5 {
6 // TODO Auto-generated method stub
7 dialog.cancel();
8 }
9 });

The alertdialog with one button looks like below.

AlertDilaog with three buttons


Add the below code snippet to your Dialog.java file to create a third Action button.

1 builder.setNeutralButton("NO",new DialogInterface.OnClickListener()
2 {
3 @Override
4 public void onClick(DialogInterface dialog, int which)
5 {
6 // TODO Auto-generated method stub
7 //Do something
8 }
9 });

The AlertDialog with three buttons looks like below:

AlertDialog with custom icon


An AlertDialog box’s icon can be changed by adding the below code snippet.

1 builder.setIcon(R.drawable.alert);

The AlertBox with custom icon looks as below.


This is how you can create an AlertDialog box in android. If you have any queries, please
post it in comment section. I hope this article would have been more useful for you to
understand the various alert dialog boxes using android programming.

- See more at: http://www.javabeat.net/alertdialog-box-android/#sthash.gY6nI2Cz.dpuf

Anda mungkin juga menyukai