The Alert Dialog Class

The AlertDialog class is one of the most versatile Dialog-class implementations. It offers a number of options that let you construct screens for some of the most common dialog-box use cases, including:

> Presenting a message to the user offering them one to three options in the form of buttons. This functionality is probably familiar to you if you've done any desktop programming for which the buttons presented are usually a combination of OK, Cancel, Yes, and No.

> Offering a list of options in the form of checkboxes or radio buttons.

> Providing a text entry box for user input.

To construct the Alert Dialog user interface, create a new AlertDialog.Builder object as follows:

AlertDialog.Builder ad = new AlertDialog.Builder(context);

You can then assign values for the title and message to display, and optionally assign values to be used for any buttons, selection items, and text input boxes you wish to display. That includes setting event listeners to handle user interaction.

Listing 5-28 gives an example of a new Alert Dialog used to display a message and offer two button options to continue. Clicking either button will close the Dialog after executing the attached Click Listener.

LISTING 5-28: Configuring an Alert Dialog

Available for download on Wrox.com

Context context = MyActivity.this; String title = "It is Pitch Black";

String message = "You are likely to be eaten by a grue.1 String buttonlString = "Go Back"; String button2String = "Move Forward";

AlertDialog.Builder ad = new AlertDialog.Builder(context)

ad.setTitle(title);

ad.setMessage(message);

ad.setPositiveButton(button1String, continues

LISTING 5-28 (continued)

new OnClickListener() {

public void onClick(DialogInterface dialog, int arg1) { eatenByGrue();

ad.setNegativeButton(button2String, new OnClickListener(){

public void onClick(DialogInterface dialog, int arg1) { // do nothing

ad.setCancelable(true);

ad.setOnCancelListener(new OnCancelListener() {

public void onCancel(DialogInterface dialog) { eatenByGrue();

To display an Alert Dialog that you've created callshow: ad.show();

A better alternative is using your Activity'sonCreateDialog and onPrepareDialog handlers to create dialog instances that can persist state. This technique is examined later in this chapter.

Mobile Apps Made Easy

Mobile Apps Made Easy

Quick start guide to skyrocket your offline and online business success with mobile apps. If you know anything about mobile devices, you’ve probably heard that famous phrase coined by one of the mobile device’s most prolific creators proclaiming that there’s an app for pretty much everything.

Get My Free Training Guide


Post a comment