Managing and Displaying Dialogs

Rather than creating new instances of a dialog each time it's required, Android provides the onCreateDialog and onPrepareDialog event handlers within the Activity class to persist and manage dialog-box instances.

By overriding the onCreateDialog handler you can specify dialogs that will be created on demand when showDialog is used to display a specific dialog. As shown in Listing 5-29, the overridden method includes a switch statement that lets you determine which dialog is required.

LISTING 5-29: Using the On Create Dialog event handler

Available for download on Wrox.com static final private int TIME_DIALOG = 1;

@Override public Dialog onCreateDialog(int id) switch(id) {

case (TIME_DIALOG) :

AlertDialog.Builder timeDialog timeDialog.setTitle("The Current Time timeDialog.setMessage("Now"); return timeDialog.create();

return null;

After the initial creation, each time showDialog is called it will trigger the onPrepareDialog handler. By overriding this method you can modify a dialog each time it is displayed. This lets you contextualize any of the display values, as shown in Listing 5-30 that assigns the current time to the dialog created in Listing 5-29.

LISTING 5-30: Using the On Prepare Dialog event handler

Available for @Override download on

Wrox.com public void onPrepareDialog(int id, Dialog dialog) { switch(id) {

case (TIME_DIALOG) :

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

continues

LISTING 5-30 (continued)

Date currentTime = new Date(java.lang.System.currentTimeMillis()); String dateString = sdf.format(currentTime); AlertDialog timeDialog = (AlertDialog)dialog; timeDialog.setMessage(dateString);

break;

Once you've overridden these methods you can display the dialogs by callingshowDialog as shown below. Pass in the identifier for the dialog you wish to display, and Android will create (if necessary) and prepare the dialog before displaying it.

showDialog(TIME_DIALOG);

As well as providing improved resource use, this technique lets your Activity handle the persistence of state information within Dialogs. Any selection or data input (such as item selection and text entry) will be persisted between displays of each Dialog instance.

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