Chapter 17

Showing Pop-Up Messages

Sometimes, your activity (or other piece of Android code) will need to speak up.

Not every interaction with Android users will be tidy and containable in fragments or activities composed of views. Errors will crop up. Background tasks may take much longer than expected. Something asynchronous may occur, such as an incoming message. In these and other cases, you may need to communicate with the user outside the bounds of the traditional user interface.

Of course, this is nothing new. Error messages in the form of dialog boxes have been around for a long time. More subtle indicators also exist, from task tray icons to bouncing dock icons to vibrating cell phones.

Android has quite a few systems for letting you alert your users outside the bounds of an Activity-based UI. One, notifications, is tied heavily into intents and services and, as such, is covered Chapter 37. In this chapter, you will learn about two means of raising pop-up messages: toasts and alerts.

Raising Toasts

A Toast is a transient message, meaning that it displays and disappears on its own without user interaction. Moreover, it does not take focus away from the currently active Activity, so if the user is busy writing the next Great Programming Guide, keystrokes will not be “eaten” by the message.

Since a Toast is transient, you have no way of knowing if the user even notices it. You get no acknowledgment from the user, nor does the message stick around for a long time to pester the user. Hence, the Toast is mostly for advisory messages, such as indicating a long-running background task is completed, the battery has dropped to a low level, and so on.

Making a Toast is fairly easy. The Toast class offers a static makeText() method that accepts a String (or string resource ID) and returns a Toast instance. The makeText() method also needs the Activity (or other Context) plus a duration. The duration is expressed in the form of the LENGTH_SHORT constant or LENGTH_LONG constant to indicate, on a relative basis, how long the message should remain visible.

If you would prefer your Toast be made out of some other View, rather than be a boring old piece of text, simply create a new Toast instance via the constructor (which takes a Context), and then call setView() to supply it with the view to use and setDuration() to set the duration.

Once your Toast is configured, call its show() method, and the message will be displayed. You will see an example of this in action later in this chapter.

Alert! Alert!

If you would prefer something in the more classic dialog box style, what you want is an AlertDialog. As with any other modal dialog box, an AlertDialog pops up, grabs the focus, and stays there until closed by the user. You might use this for a critical error, a validation message that cannot be effectively displayed in the base activity UI, or some other situation where you are sure that the user needs to see the message immediately.

The simplest way to construct an AlertDialog is to use the Builder class. Following in true builder style, Builder offers a series of methods to configure an AlertDialog, each method returning the Builder for easy chaining. At the end, you call show() on the builder to display the dialog box.

Commonly used configuration methods on Builder include the following:

  • setMessage(): Sets the “body” of the dialog box to be a simple textual message, from either a supplied String or a supplied string resource ID
  • setTitle() and setIcon(): Configure the text and/or icon to appear in the title bar of the dialog box
  • setPositiveButton() and setNegativeButton(): Indicate which button(s) should appear across the bottom of the dialog box, where they should be positioned (left, center, or right, respectively), what their captions should be, and what logic should be invoked when the button is clicked (besides dismissing the dialog box).

If you need to configure the AlertDialog beyond what the builder allows, instead of calling show(), call create() to get the partially built AlertDialog instance, configure it the rest of the way, and then call one of the flavors of show() on the AlertDialog itself. Once show() is called, the dialog box will appear and await user input.

Note that pressing any of the buttons will close the dialog box, even if you have registered a listener for the button in question. Hence, if all you need a button to do is close the dialog box, give it a caption and a null listener. There is no option, with AlertDialog, to have a button at the bottom invoke a listener yet not close the dialog box.

Checking Them Out

To see how these work in practice, take a peek at Messages/Message, containing the following layout:

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/alert"
  android:text="Raise an alert"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:onClick="showAlert"
/>

The following is the Java code:

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    setContentView(R.layout.main);
  }

  public void showAlert(View view) {
    new AlertDialog.Builder(this)
      .setTitle("MessageDemo")
      .setMessage("Let's raise a toast!")
      .setNeutralButton("Here, here!", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dlg, int sumthin) {
          Toast
            .makeText(MessageDemo.this, "<clink, clink>",
                     Toast.LENGTH_SHORT)
            .show();
        }
      })
      .show();
  }
}

The layout is unremarkable—just a really large Button to show the AlertDialog. However, Ice Cream Sandwich adds two new options to the AlertDialog(context, int) form of invocation. These options support device-wide “light” and “dark” backgrounds for alerts via the THEME_DEVICE_DEFAULT_LIGHT and THEME_DEVICE_DEFAULT_DARK values. These options aid in promoting the notion of seamless experience across the whole Android device.

When you click the Button, we use a builder (new Builder(this)) to set the title (setTitle("MessageDemo")), message (setMessage("Let's raise a toast!")), and neutral button (setNeutralButton("Here, here!", new OnClickListener() ...) before showing the dialog box. When the button is clicked, the OnClickListener callback triggers the Toast class to make us a text-based toast (makeText(this, "<clink, clink>", LENGTH_SHORT)), which we then show(). The result is a typical dialog box, as shown in Figure 17–1.

images

Figure 17–1. The MessageDemo sample application, after clicking the Raise an alert button

When you close the dialog box via the button, it raises the toast, as shown in Figure 17–2.

images

Figure 17–2. The same application, after clicking the Make a toast button

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

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