Adding buttons

Are you sure you want to exit?

hid

To create an AlertDialog with side-by-side buttons like the one shown in the screenshot to the right, use the set...Button() methods:

AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Are you sure you want to exit?") .setCancelable(false)

.setPositiveButton("Yes", new DialogInterface.OnClickListener()) { public void onClick(DialogInterface dialog, int id) {

MyActivity.this.finish();

.setNegativeButton("No", new DialogInterface.OnClickListener()){ public void onClick(DialogInterface dialog, int id) { dialog.cancel();

AlertDialog alert = builder.create();

First, add a message for the dialog with setMessage(CharSeguence). Then, begin method-chaining and set the dialog to be not cancelable (so the user cannot close the dialog with the back button) with setCancelablefboolean). For each button, use one of the set.. .Button() methods, such as setPositiveButtonf), that accepts the name for the button and a Dialoglnterface.OnClickListener that defines the action to take when the user selects the button.

Note: You can only add one of each button type to the AlertDialog. That is, you cannot have more than one "positive" button. This limits the number of possible buttons to three: positive, neutral, and negative. These names are technically irrelevant to the actual functionality of your buttons, but should help you keep track of which one does what.

Green

Blue

To create an AlertDialog with a list of selectable items like the one shown to the right, use the setItems() method:

final CharSequence[] items = {"Red", "Green", "Blue"}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Pick a color");

builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) {

Toast.makeText(getApplicationContext(), items[item],

AlertDialog alert = builder.create();

First, add a title to the dialog with setTitle(CharSequence). Then, add a list of selectable items with setItemsO, which accepts the array of items to display and a DialogInterface.OnClickListener that defines the action to take when the user selects an item.

0 0

Post a comment