Recipe Using an Alert Dialog

Providing a user with an alert and up to three buttons of possible actions can be done with the AlertDialog class. Some examples are

■ "Your final score was 80/100:Try this level again, advance to next level, or go back to the main menu."

■ "The image file is corrupt, choose another or cancel action."

This recipe takes the first example and shows how to provide an action on each choice depending on which button is clicked.The example code is shown in Listing 3.20.

The AlertDialog is initialized using the create() method; the text is specified using the setMessage() method; the three possible button text and corresponding actions are specified using the setButton() method; and finally, the dialog box is displayed to the screen using the show() method. Note the logic in each of the onClick() callback functions is just an example to show how to specify button actions.

Listing 3.20 Example of AlertDialog

AlertDialog dialog = new AlertDialog.Builder(this).create();

dialog.setMessage("Your final score: " + mScore + "/" + PERFECT_SCORE); dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try this level again", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {

dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Advance to next level", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {

dialog.setButton(DialogInterface.BUTTON_NEUTRAL, "Back to the main menu", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {

dialog.show();

This produces the pop-up dialog box shown in Figure 3.3. Note that the buttons are displayed in the order button_positive, button_neutral, and button_negative. If a dialog box with two options or one option is needed, do not specify all three button choices.

Figure 3.3 Example of an alert dialog box.
Character Building Thought Power

Character Building Thought Power

Character-Building Thought Power by Ralph Waldo Trine. Ralph draws a distinct line between bad and good habits. In this book, every effort is made by the writer to explain what comprises good habits and why every one needs it early in life. It draws the conclusion that habits nurtured in early life concretize into impulses in future for the good or bad of the subject.

Get My Free Ebook


Post a comment