Android Graphics Tutorial: Dialogs

PrevMainNext

What are Dialogs?

Almost every Android application needs to interact with the users. While toasts (covered in Android UI Controls Tutorial) are good for notification purposes, they do not solicit any action from users. When you need the application user to make a choice or confirm/ reject any action, you need to use Dialogs.

Simply put, a Dialog is a small window that appears in front of the current Activity. From the user perspective, the dialog pushes the current activity into background and gains focus, thereby forcing the user to perform some application before the application makes further progress.

In this section, we cover the various types of Dialogs commonly used in Android application development.

Alert

As the name itself suggests, an Alert is a kind of dialog that’s intended to alert the user about some specific event. It usually consists of 1-3 buttons and a string message.

Here’s how you create an alertDialog for your Android application.

Declare an alertDialog object.

AlertDialog alertDialog = new AlertDialog.Builder(Main.this).create();

In the above statement, the Main.this refers to the main activity’s context. Next, set a title for your alert by using the setTitle() method.

alertDialog.setTitle("Demo Alert");

Set the message for your alert as shown below:

alertDialog.setMessage("Choose an option");

Add a button and an onClick() action for that button.

  alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int which) {
       // add your own logic here
      } 
  });

You can change the icon of alert if needed as shown below:

alertDialog.setIcon(R.drawable.icon);

To show your alert, call the show() method:

alertDialog.show();

Your alertDialog would then show up as follows.

alert Dialog

Custom Dialog

In many cases, developers would prefer to create their own custom dialogs instead of using the pre-built ones. This can be achieved by creating a layout xml for the dialog window and the required widget elements as shown below.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <EditText android:id="@+id/EditText01" 
        android:layout_height="wrap_content" 
        android:text="Enter your name" 
        android:layout_width="250dip"></EditText>

    <Button android:id="@+id/Button01" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:text="click"></Button>

</LinearLayout>

Next, create your own custom Dialog implementation by extending the Dialog and specify the custom layout.

public class SampleCustomDialog extends Dialog {

    public interface ReadyListener {
        public void ready(String name);
    }

    private String name;
    private ReadyListener readyListener;
    EditText etName;

    public SampleCustomDialog(Context context, String name, 
            ReadyListener readyListener) {
        super(context);
        this.name = name;
        this.readyListener = readyListener;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.samplecustomdialog);
        setTitle("Hello, this is a custom dialog!");
        Button buttonOK = (Button) findViewById(R.id.Button01);
        buttonOK.setOnClickListener(new OKListener());
        etName = (EditText) findViewById(R.id.EditText01);
    }

    private class OKListener implements android.view.View.OnClickListener {
        @Override
        public void onClick(View v) {
            readyListener.ready(String.valueOf(etName.getText()));
            SampleCustomDialog.this.dismiss();
        }
    }
}

The next step is to create your MainActivity and instantiate your custom dialog object.

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        SampleCustomDialog sampleDialog = new SampleCustomDialog(this, "",
                new OnReadyListener());
        sampleDialog.show();
    }

    private class OnReadyListener implements SampleCustomDialog.ReadyListener {
        @Override
        public void ready(String name) {
            Toast.makeText(MainActivity.this, name, Toast.LENGTH_LONG).show();
        }
    }
}

Your custom dialog would then show up as follows:

custom dialog

List

As a developer, you may want to show a dialog which allows multiple selections in a ListView. To do so, create a dialog box which in turn calls the onCreateDialog method in the main class. Let’s use numbers – one, two and three as the list options for the dialog box.

@Override
protected Dialog onCreateDialog(int id) {
      return new AlertDialog.Builder(this)
          .setTitle("Select One Digit")
          .setMultiChoiceItems(_options, _selections, new DialogSelectionClickHandler())
          .setPositiveButton("OK", new DialogButtonClickHandler())
          .create();
}

Let’s create a list for the values that need to be populated in the ListView:

protected CharSequence[] _options = {"One", "Two", "Three"};
protected boolean[] _selections =  new boolean[_options.length];

Next, create a custom click handler which would get triggered each time an item is selected or deselected:

public class DialogButtonClickHandler implements DialogInterface.OnClickListener {
	public void onClick(DialogInterface dialog, int clicked) {
		switch (clicked) {
			case DialogInterface.BUTTON_POSITIVE:
				printSelectedPlanets();
				break;
		}
	}
}

protected void printSelectedNumbers () {
        for (int i = 0; i < _options.length; i++) {
	      Log.i("ME", _options[ i ] + " selected: " + _selections[i]);
	}
}

Your list dialog would then show up as follows:

list dialog

Radio

This is similar to the List Dialog except that it allows only one item to be selected. The trick is to use the setSingleChoiceItems() method instead of the setMultiChoiceItems() that’s used in case of list dialogs.

PrevMainNext