Login     Sign Up
Cyril Sermon (@admin)
9 months ago

Introducing the Dialog Class

The Dialog class implements a simple floating window that is constructed entirely within an Activity.

To use the base Dialog class, you create a new instance and set the title and layout as shown below:

Dialog d = new Dialog(MyActivity.this);

Have the new window tint and blur the window it obscures.

Window window = d.getWindow(); window.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,


d.setTitle(“Dialog Title”);


TextView text = (TextView)d.findViewById(R.id.dialogTextView); text.setText(“This is the text in my dialog”);

Once it’s configured to your liking, use the show method to display it.


The AlertDialog Class

The AlertDialog class is one of the most versatile Dialog implementations. It offers various options that let you construct screens for some of the most common Dialog-box use cases, including:

❑Presenting a message to the user offering one to three options in the form of alternative buttons. This functionality is probably familiar to you if you’ve done any desktop programming, where the buttons presented are usually a selection of OK, Cancel, Yes, or No.

❑ Offering a list of options in the form of check buttons or radio buttons. ❑ Providing a text entry box for user input.

To construct the Alert Dialog user interface, create a new AlertDialog.Builder object, as shown below:

AlertDialog.Builder ad = new AlertDialog.Builder(context);

You can then assign values for the title and message to display, and optionally assign values to be used for any buttons, selection items, and text input boxes you wish to display. That includes setting event listeners to handle user interaction.

The following code gives an example of a new Alert Dialog used to display a message and offer two button options to continue. Clicking on either button will automatically close the Dialog after executing the attached Click Listener.

Context context = MyActivity.this;

String title = “It is Pitch Black”;

String message = “You are likely to be eaten by a grue.”;

String button1String = “Go Back”;

String button2String = “Move Forward”;

AlertDialog.Builder ad = new AlertDialog.Builder(context);




new OnClickListener() {

public void onClick(DialogInterface dialog,

int arg1) {





new OnClickListener(){

public void onClick(DialogInterface dialog,

int arg1) {

// do nothing




ad.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) { eatenByGrue();



To display an Alert Dialog that you’ve created call show.


Alternatively, you can override the onCreateDialog and onPrepareDialog methods within your Activity to create single-instance Dialogs that persist their state. This technique is examined later in this chapter.

Specialist Input Dialogs

One of the major uses of Dialog boxes is to provide an interface for user input. Android includes several specialist Dialog boxes that encapsulate controls designed to facilitate common user input requests. They include the following:

❑DatePickerDialog Lets users select a date from a DatePicker View. The constructor includes a callback listener to alert your calling Activity when the date has been set.

❑TimePickerDialog Similar to the DatePickerDialog, this Dialog lets users select a time from a TimePicker View.

❑ProgressDialog A Dialog that displays a progress bar beneath a message textbox. Perfect for keeping the user informed of the ongoing progress of a time-consuming operation.

Using and Managing 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 class, you can specify Dialogs that will be created on demand when showDialog is used to display a specific Dialog. As shown in this code snippet, the overridden method includes a switch statement that lets you determine which Dialog is required:

static final private int TIME_DIALOG = 1;


public Dialog onCreateDialog(int id) {

switch(id) {

case (TIME_DIALOG) :

AlertDialog.Builder timeDialog = new AlertDialog.Builder(this);

timeDialog.setTitle(“The Current Time Is...”);


return timeDialog.create();


return null;


After the initial creation, each time a showDialog is called, it will trigger the onPrepareDialog han-dler. By overriding this method, you can modify a Dialog immediately before it is displayed. This lets you contextualize any of the display values, as shown in the following snippet, which assigns the cur-rent time to the Dialog created above:


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

case (TIME_DIALOG) :

SimpleDateFormat sdf = new SimpleDateFormat(“HH:mm:ss”); Date currentTime;

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





Once you’ve overridden these methods, you can display the Dialogs by calling showDialog, 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:


As well as improving 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.

Using Activities as Dialogs

Dialogs offer a simple and lightweight technique for displaying screens, but there will still be times when you need more control over the content and life cycle of your Dialog box.

The solution is to implement it as a full Activity. By creating an Activity, you lose the lightweight nature of the Dialog class, but you gain the ability to implement any screen you want and full access to the Activity life-cycle event handlers.

So, when is an Activity a Dialog? The easiest way to make an Activity look like a Dialog is to apply the android:style/Theme.Dialog theme when you add it to your manifest, as shown in the following XML snippet:

<activity android:name=”MyDialogActivity” android:theme=”@android:style/Theme.Dialog”>


This will cause your Activity to behave like a Dialog, floating on top of, and partially obscuring, the Activity beneath it.