1 of 9

Alert Dialog�

K.R.Prasanna Kumar

AP/IT

2 of 9

Dialogs

  • A Dialog is small window that prompts the user to a decision or enter additional information.
  • A dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed.
  • Dialog class is the base class for dialogs, but you should avoid instantiating Dialog directly.

3 of 9

Building an Alert Dialog

  • The AlertDialog class allows you to build a variety of dialog designs and is often the only dialog class you'll need.
  • Title This is optional and should be used only when the content area is occupied by a detailed message, a list, or custom layout. If you need to state a simple message or question (such as the dialog in figure 1), you don't need a title.
  • Content area This can display a message, a list, or other custom layout.
  • Action buttons There should be no more than three action buttons in a dialog.

4 of 9

  • setTitle(CharSequence title)
    • This method set the title to be appear in the dialog
  • setMessage(CharSequence message)
    • This method sets the message to be displayed in the alert dialog
  • setIcon(Drawable icon)
    • This method set the icon of the alert dialog box.

5 of 9

AlertDialog.Builder builder = new AlertDialog.Builder(this);�

builder.setMessage(R.string.dialog_message)�       .setTitle(R.string.dialog_title);

AlertDialog dialog = builder.create();

6 of 9

Action Buttons

  • Positive - setPositiveButton()
    • accept and continue with the action (the "OK" action).
  • Negative - setNegativeButton()
    • cancel the action.
  • Neutral
    • You should use this when the user may not want to proceed with the action, but doesn't necessarily want to cancel.
    • It appears between the positive and negative buttons. For example, the action might be "Remind me later."

7 of 9

  • Adding a list
    • There are three kinds of lists available with the AlertDialog APIs:
    • A traditional single-choice list
    • A persistent single-choice list (radio buttons)
    • A persistent multiple-choice list (checkboxes)

8 of 9

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());�// Add the buttons

�builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {�           public void onClick(DialogInterface dialog, int id) {�               // User clicked OK button�           }�       });

�builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {�           public void onClick(DialogInterface dialog, int id) {�               // User cancelled the dialog�           }�       });

�// Set other dialog properties�...��// Create the AlertDialog�AlertDialog dialog = builder.create();�

9 of 9

  • AlertDialog.Builder class provides APIs that allow you to create an AlertDialog with these kinds of content, including a custom layout.