Designing an Alert Dialog

We will begin our exploration with alert dialogs. Alert dialogs commonly contain simple messages about validating forms or debugging. Consider the following debug example that you often find in HTML pages:

//indicate that formatting is not valid through an alert dialog showAlert("What you have entered in fieldl doesn't match required format"); //set focus to the field //..and continue

You would likely program this dialog in JavaScript through the alert function, which displays a simple synchronous dialog box containing a message and an OK button. After the user clicks the OK button, the flow of the program continues. This dialog is considered modal as well as synchronous because the next line of code will not be executed until the alert function returns.

This type of alert dialog proves useful for debugging. But Android offers no such direct function or dialog. Instead, it supports an alert-dialog builder, a general-purpose facility for constructing and working with alert dialogs. So you can build an alert dialog yourself using the android.app.AlertDialog.Builder class. You can use this builder class to construct dialogs that allow users to perform the following tasks:

• Read a message and respond with Yes or No

• Pick multiple items from a list

• View the progress of an application

• Choose an option from a set of options

• Respond to a prompt before continuing the program

We will show you how to build one of these dialogs and invoke that dialog from a menu item. This approach, which applies to any of these dialogs, consists of these steps:

1. Construct a Builder object.

2. Set parameters for the display such as the number of buttons, the list of items, and so on.

3. Set the callback methods for the buttons.

4. Tell the Builder to build the dialog. The type of dialog that's built depends on what you've set on the Builder object.

5. Use dialog.show() to show the dialog.

Listing 5-21 shows the code that implements these steps.

Listing 5-21. Building and Displaying an Alert Dialog public class Alerts {

public static void showAlert(String message, Context ctx)

0 0

Post a comment