Creating an Alert Dialog Box

From time to time it may be necessary to alert the user to something that has happened. In the Task Reminder app, perhaps you want to display a welcome message and offer instructions on how to create a task. The Android system has a framework, built around dialog boxes that provide you with the implementation you may need.

Various types of dialog boxes are available:

check.png Alert: Notifies the user of an important occurrence. Also allows you to set the text value of a button and the action to be performed when it’s clicked. As a developer, you can provide the AlertDialog with a list of items to display, allowing the user to select from a list of items.

check.png Progress: Used to display a progress wheel or bar. This type of dialog box is created via the ProgressDialog class.

check.png Custom: A custom dialog box created and programmed by you, the master Android developer. You create a custom dialog box class by extending the Dialog base class or using custom layout XML files.

Seeing why you should work with dialog boxes

If you’ve never worked with an application that failed to alert you, or warn you appropriately, consider the example of an e-mail client not notifying you that you have new e-mail. How annoying would that be? Alerting users to important issues or choices that need to be made is an integral part of any user experience.

This list gives a few examples of using a dialog box to inform the user of a message or a necessary action:

check.png Something is happening in the background. (The ProgressDialog does this.)

check.png The values in an EditText view are invalid.

check.png The network has become unavailable.

check.png The user needs to select a date or time (as in the Task Reminder app).

check.png The state of the phone is incompatible with the application. (It might need to have GPS enabled or an SD card added, for example.)

check.png The user needs to choose from a list of items.

Though this list isn’t comprehensive, it gives you an inkling into what is possible with dialog boxes.

tip.eps When you work with any type of blocking process (network communication or long-running tasks, for example), always provide the user with an informative dialog box or progress indicator. A user who doesn’t realize that an element of your app needs attention is likely to mistakenly believe that it has stopped responding and could even uninstall it. The Android framework provides various progress indicators, such as the common progress classes ProgressDialog and ProgressBar.

technicalstuff.eps Though a discussion of the AsyncTask class is beyond the scope of this book, you would use this class to manage long-running tasks while updating the user interface. (See the helpful “Painless Threading” tutorial at http://android-developers.blogspot.com/2009/05/painless-threading.html .) You can also create a new thread in code — the AsyncTask class helps simplify this process.

Choosing the appropriate dialog box for a task

Though you determine which dialog box to use for a given scenario, you can ask a logical series of questions to choose the appropriate one:

1. Is this task long-running?

Yes: Use ProgressDialog to let the user know that something is happening in the background and that the app isn’t frozen. A great resource that explains how to do this is located here: http://d.android.com/guide/topics/ui/dialogs.html#ProgressDialog .

No: Continue to Step 2.

2. Does the user need to be able to perform an advanced action in the dialog box?

An advanced action isn’t supported by the AlertDialog class.

Yes: Create a custom Dialog class by extending the Dialog base class or creating one from a custom layout XML file. You can find more information about custom dialog boxes at http://d.android.com/guide/topics/ui/dialogs.html#CustomDialog .

No: Continue to Step 3.

3. Does the user need to answer a question such as “Are you sure?” with a Yes or No value?

Yes: Create an AlertDialog and react to the buttons on the AlertDialog by using onClickListener() calls.

No: Continue to Step 4.

4. Does the user need to make a selection from a simple list of items?

Yes: Create an AlertDialog.

No: Continue to Step 5.

5. Does the user simply need to be alerted?

Yes: Create a simple AlertDialog.

No: You may not need a dialog box, if you can notify the user another way.

Creating your own alert dialog box

At times, you need to notify the user of important information by presenting a dialog box. Android makes it quite simple with its introduction of the AlertDialog.Builder class, which lets you easily create an AlertDialog with various options and buttons. Your app can react to these button clicks via the onClickListener() of each button.

You don’t need to use the AlertDialog.Builder class in a simple application, such as Task Reminder. However, Listing 11-5 shows how to create one when you create more complex applications.

Suppose that the user has tapped the Save button in the Task Reminder application and you want to open a window (similar to the one in Figure 11-3) so that the user can confirm.

In Listing 11-5, you create an AlertDialog object using the AlertDialog.Builder class and then add an AlertDialogFragment (which works similarly to DatePickerDialogFragment and TimePickerDialogFragment).

Listing 11-5: Creating an AlertDialogFragment with the AlertDialog. Builder Class

public class AlertDialogFragment extends DialogFragment {

@Override

public Dialog onCreateDialog(Bundle savedInstanceState) {

AlertDialog.Builder builder

= new AlertDialog.Builder(getActivity()); →5

builder.setMessage(“Are you sure you want to save the task?”) →6

.setTitle(“Are you sure?”) →7

.setCancelable(false) →8

.setPositiveButton(“Yes”, →9

new DialogInterface.OnClickListener() { →10

public void onClick(DialogInterface dialog, int id) {

// Perform some action such as saving the item →12

}

})

.setNegativeButton(“No”, new DialogInterface.OnClickListener() { →15

public void onClick(DialogInterface dialog, int id) {

dialog.cancel(); →17

}

});

return builder.create(); →20

}

}

Figure 11-3: The confirmation Alert Dialog window.

9781118417454-fg1103.tif

The code is explained in this list:

5 Sets up the AlertDialog.Builder class with the context of the AlertDialog.Builder as the current running activity.

6 Specifies the message to show in the middle of the AlertDialog (as shown in Figure 11-3). The value can be a string or a string resource.

7 Sets the title of the AlertDialog. The value can be a string or a string resource.

8 Sets the cancelable attribute to false, requiring the user to select a button in the AlertDialog. If this flag is set to false, the user cannot tap the Back button on the device to exit the AlertDialog. Set it to true and the user can tap the Back button.

9 Specifies the text on the positive button. The user clicks the Yes button to perform the action indicated on line 10. This value can be a string or a string resource.

10 A block of code (ending on line 12) that defines the onClick Listener() for the Yes button. The code on line 12 executes when the button is tapped.

15 Specifies the text on the negative button. This button indicates that the user doesn’t want to perform the action being requested via AlertDialog. The text value of this button is set to No. It can be a string or a string resource.

17 Sets the onClickListener() for the negative button. The listener provides a reference to the dialog box that’s being shown. It’s called the cancel() method on the Dialog object to close the dialog box when the user clicks No on the AlertDialog.

20 Notifies Android to create the AlertDialog via the create() method.

To show the dialog box, you start a fragment transaction in the usual manner:

FragmentTransaction ft = getFragmentManager().beginTransaction();

DialogFragment newFragment = new AlertDialogFragment();

newFragment.show(ft, “alertDialog”);

tip.eps Creating a dialog box with the AlertDialog.Builder class is easier than having to derive your own Dialog class. If possible, create your dialog box with the AlertDialog.Builder class because it gives your application a consistent user experience that’s familiar to most Android users.

When the user taps the Save button (or whatever button the code is attached to), an AlertDialog opens so that the user can confirm saving the task. This data most likely is stored in a database, as covered in Chapter 12.

You can find helpful examples of using other options on the Dialog class at http://d.android.com/guide/topics/ui/dialogs.html .

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset