Click here to Skip to main content
15,880,651 members
Articles / Mobile Apps / Android

Using Alerts in Android

Rate me:
Please Sign up or sign in to vote.
4.71/5 (7 votes)
5 Sep 2010CPOL3 min read 103K   2.5K   36   4
Tutorial on using alerts in Android

Introduction

Amdroid introduces a way to show interactive messages is to use Alerts. Alerts act as MessageBox or JOptionPane in J2SE. They have buttons that can be used to take decisions.

Creating Alerts

Let's check this example to create an alert and show it:

Java
//declared as final to be able to reference it in inner 
//class declartations of the handlers 
final AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Alert Dialog");
builder.setMessage("This is the alert's body");
builder.setIcon(android.R.drawable.ic_dialog_alert);

builder.setPositiveButton("OK", new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
TextView txt=(TextView)findViewById(R.id.txt);
txt.setText("You clicked Ok");
}
});

builder.setNegativeButton("Cancel", new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
TextView txt=(TextView)findViewById(R.id.txt);
txt.setText("You clicked Cancel");
}
});

builder.setNeutralButton("Do something", new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
TextView txt=(TextView)findViewById(R.id.txt);
txt.setText("Neutral Button Clicked");
AlertDialog ad=builder.create();
ad.cancel();
}
});

builder.setOnCancelListener(new OnCancelListener() {

@Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
TextView txt=(TextView)findViewById(R.id.txt);
txt.setText(txt.getText()+" the cancel listner invoked");
}
});

builder.show();

The previous code displays the following Alert:

alerts1.png

The code may look bulky, but it's very simple. First, we create an instance of AlertDialog.Builder. We use the builder object to construct the AlertDialog object.

We specify the title and the icon of the alert, then the text to display in the body of the message.

The AlertDialog can display up to three buttons:

  • Positive button: Represents the OK button.
  • Negative button: Represents the cancel button.
  • Neutral button: Represents a button to perform another functionality other than ok or cancel.

Note that there are no restrictions on the use of the three buttons. They can perform the same functionality; the difference is just in logical meaning. But the three buttons cause the Alert dialog to dismiss.

We then specify the text and the click handler of each button. In the neutral button click handler, we added the lines AlertDialog ad=builder.create(); and ad.cancel();. The first line gets a reference to the current dialog created by the builder to provide additional functionality such as invoking cancel() method. The cancel method raises the onCancel callback method. We could have replaced the previous code with the following:

Java
ad.setMessage(message);
ad.setIcon(icon);
ad.setMessage(message);
ad.setButton(text, listener);
.
.
.

Displaying Custom Views

Alerts can display complex views rather than simple text messages. Create an XML layout file called alertview.xml like this:

XML
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=
	"http://schemas.android.com/apk/res/android" android:orientation="vertical" 
	android:layout_width="fill_parent" android:layout_height="fill_parent" 
	android:id="@+id/toastView" android:background="#DAAA" > 
	<TextView android:layout_width="fill_parent" 
	android:layout_height="wrap_content" android:text="Hello alerts" 
	android:textColor="#000" /> <TextView android:layout_width="fill_parent" 
	android:layout_height="wrap_content" android:id="@+id/txtDate" 
	android:textColor="#000" /> <Button android:layout_width="fill_parent" 
	android:layout_height="wrap_content" android:id="@+id/btnAlert" 
	android:text="Click" /> </LinearLayout> 

To display this view as the alert view, we do it like this:

Java
View bodyView=getLayoutInflater().inflate
	(R.layout.alertview, (ViewGroup)findViewById(R.id.toastView));

TextView txtDate=(TextView)bodyView.findViewById(R.id.txtDate);
txtDate.setText(Calendar.getInstance().getTime().toLocaleString());
Button btnAlert=(Button)bodyView.findViewById(R.id.btnAlert);
btnAlert.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
TextView txtDate=(TextView)bodyView.findViewById(R.id.txtDate);
txtDate.setText(Calendar.getInstance().getTime().toLocaleString());
TextView txt=(TextView)findViewById(R.id.txt);
txt.setText(Calendar.getInstance().getTime().toLocaleString());
}
});
builder.setView(bodyView);
.
.
.

What is interesting in this approach is that the alert is fully interactive. By clicking the button, you can change the value of any view in the alert or in the activity.

You can also set the title of the alert to be a custom view via builder.setCustomTitle(View v) method in the same way described above.

Displaying an Alert of Items

Alerts can display a list of items from which the user selects from like this:

Java
final String [] items=new String []{"Item 1","Item 2","Item 3","Item 4"};
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Items alert");

builder.setItems(items, new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
TextView txt=(TextView)findViewById(R.id.txt);
txt.setText(items[which]);
}
});

builder.show();

This will display an alert like this:

alerts2.png

Notice that we do not have to specify any buttons because when the user clicks on any item, the alert will be dismissed.

If the list items are in an Adapter, we can achieve the same result using builder.setAdapter(Adapter ad,OnClickListener listner) method:

Java
final String [] items=new String []{"Item 1","Item 2","Item 3","Item 4"};
ArrayAdapter<string> arr=new ArrayAdapter<string>
	(this, android.R.layout.select_dialog_item,items);

AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Adapter alert");

builder.setAdapter(arr, new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
TextView txt=(TextView)findViewById(R.id.txt);
txt.setText(items[which]);
}
});

or if the items are returned from a database in a cursor, we can use builder.setCursor(Cursor cursor, OnClickListener listner, String labelColumn).

Displaying Alerts with Items with Choices

We can add items to the alert with choices whether they are single choice (Radio buttons) or multiple choices (Check boxes).

To display single choice items:

Java
final String [] items=new String []{"Item 1","Item 2","Item 3","Item 4"};
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("List alert");
builder.setSingleChoiceItems(items, 0, new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
TextView txt=(TextView)findViewById(R.id.txt);
txt.setText(items[which]);
}
});
builder.setPositiveButton("OK", new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.show();

The second parameter of setSingleChoiceItems is an integer specifying the index of the selected item. Notice that we added a postive button that when clicked, dismisses the alert cause unlike the regular items list, the alert won't be dismissed when an item is selected.

The builder.setSingleChoiceItems method has other overloads that can accept an Adapter or a Cursor as parameters that hold the items to be displayed.

To display multiple choice items:

Java
final String [] items=new String []{"Item 1","Item 2","Item 3","Item 4"};
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("List alert");
builder.setMultiChoiceItems(items, null, new OnMultiChoiceClickListener() {

@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// TODO Auto-generated method stub
TextView txt=(TextView)findViewById(R.id.txt);
txt.setText(txt.getText()+" "+items[which]);
}
});
builder.setPositiveButton("OK", new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub

}
});
builder.show();

The second parameter of setMultiChoiceItems is an array of boolean values specifying which items are set selected.

If you want no items to be selected, then set it to null, otherwise specify an array with the same length of the items with boolean values indicating which item is selected and which is not like this:

Java
new boolean[] {true,false,...}

This works in the fashion as single items choice except that the selection here is multiple.

View more tutorials on http://android-pro.blogspot.com/.

History

  • 6th September, 2010: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer ITWORX
Egypt Egypt
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Hatem Mostafa28-Mar-12 0:04
Hatem Mostafa28-Mar-12 0:04 
GeneralMy vote of 1 PinPopular
touchyp5-Sep-10 23:16
touchyp5-Sep-10 23:16 
GeneralMy vote of 5 Pin
GPUToaster™5-Sep-10 22:55
GPUToaster™5-Sep-10 22:55 
GeneralRe: My vote of 5 Pin
Mina Samy5-Sep-10 23:06
Mina Samy5-Sep-10 23:06 
You're welcome
I'm glad you liked it

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.