Recasting the Nonmanaged Dialog as a Managed Dialog

We will follow each of the steps laid out to reimplement the alert dialog. Let's start by defining a unique ID for this dialog in the context of a given activity:

//unique dialog id private static final int DIALOG_ALERT_ID = 1;

That is simple enough. We have just created an ID to represent a dialog to orchestrate the callbacks. This ID will allow us to do the following in response to a menu item:

if (item.getItemId() ==


The Android SDK method showDialog triggers a call to the onCreateDialog() method. Android is smart enough not to call onCreateDialog() multiple times. When this method is called, we need to create the dialog and return it to Android. Android then keeps the created dialog internally for reuse purposes. Here is the sample code to create the dialog based on a unique ID:

^Override protected Dialog onCreateDialog(int id) { switch (id) {


return createAlertDialog();

return null;

private Dialog createAlertDialog()

AlertDialog.Builder builder = new AlertDialog.Builder(this); builder. setTitle("Alert"); builder.setMessage("some message");

EmptyOnClickListener emptyListener = new EmptyOnClickListener(); builder.setPositiveButton("Ok", emptyListener ); AlertDialog ad = builder.create(); return ad;

Notice how onCreateDialog() has to figure out the incoming ID to identify a matching dialog. createAlertDialog() itself is kept in a separate function and parallels the alert-dialog creation described in the previous sections. This code also uses the same EmptyOnClickListener that was used when we worked with the alert dialog.

Because the dialog is created only once, you need a mechanism if you want to change something in the dialog every time you show it. You do this through the onPrepareDialog() callback method:

^Override protected void onPrepareDialog(int id, Dialog dialog) { switch (id) { case DIALOG_ALERT_ID:


private void prepareAlertDialog(Dialog d) { AlertDialog ad = (AlertDialog)d; //change something about this dialog

With this code in place, showDialog(l) will work. Even if you were to invoke this method multiple times, your onCreateMethod will get called only once. You can follow the same protocol to redo the prompt dialog.

So responding to dialog callbacks is work, but the managed-dialog protocol adds even more work. After looking at the managed-dialog protocol, we got the idea to abstract out the protocol and rearrange it in such a way that it accomplishes two goals:

• Moving the dialog identification and creation out of the activity class

• Concentrating the dialog creation and response in a dedicated dialog class

In the next subsection, we will go through the design of this framework and then use it to re-create both the alert and prompt dialogs.

0 0

Post a comment