14.01.2013 Views

Android™ Application Development - Bahar Ali Khan

Android™ Application Development - Bahar Ali Khan

Android™ Application Development - Bahar Ali Khan

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 5: Intents, Broadcast Receivers, Adapters, and the Internet<br />

After the initial creation, each time a showDialog is called, it will trigger the onPrepareDialog handler.<br />

By overriding this method, you can modify a Dialog immediately before it is displayed. This lets<br />

you contextualize any of the display values, as shown in the following snippet, which assigns the current<br />

time to the Dialog created above:<br />

@Override<br />

public void onPrepareDialog(int id, Dialog dialog) {<br />

switch(id) {<br />

case (TIME_DIALOG) :<br />

SimpleDateFormat sdf = new SimpleDateFormat(“HH:mm:ss”);<br />

Date currentTime;<br />

currentTime = new Date(java.lang.System.currentTimeMillis());<br />

String dateString = sdf.format(currentTime);<br />

AlertDialog timeDialog = (AlertDialog)dialog;<br />

timeDialog.setMessage(dateString);<br />

}<br />

}<br />

break;<br />

Once you’ve overridden these methods, you can display the Dialogs by calling showDialog, as shown<br />

below. Pass in the identifi er for the Dialog you wish to display, and Android will create (if necessary)<br />

and prepare the Dialog before displaying it:<br />

showDialog(TIME_DIALOG);<br />

As well as improving resource use, this technique lets your Activity handle the persistence of state<br />

information within Dialogs. Any selection or data input (such as item selection and text entry) will be<br />

persisted between displays of each Dialog instance.<br />

Using Activities as Dialogs<br />

Dialogs offer a simple and lightweight technique for displaying screens, but there will still be times<br />

when you need more control over the content and life cycle of your Dialog box.<br />

The solution is to implement it as a full Activity. By creating an Activity, you lose the lightweight nature<br />

of the Dialog class, but you gain the ability to implement any screen you want and full access to the<br />

Activity life-cycle event handlers.<br />

So, when is an Activity a Dialog? The easiest way to make an Activity look like a Dialog is to apply the<br />

android:style/Theme.Dialog theme when you add it to your manifest, as shown in the following<br />

XML snippet:<br />

<br />

<br />

This will cause your Activity to behave like a Dialog, fl oating on top of, and partially obscuring, the<br />

Activity beneath it.<br />

147

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!