Adding a list

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], Toast.LENGTH_SHORT).show(); }

AlertDialog alert = builder.create();

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

Adding checkboxes and radio buttons

To create a list of multiple-choice items (checkboxes) or single-choice items (radio buttons) inside the dialog, use the setMultiChoiceItems() and setSingleChoiceltemsO methods, respectively. If you create one of these selectable lists in the onCreateDialog() callback method, Android manages the state of the list for you. As long as the Activity is active, the dialog remembers the items that were previously selected, but when the user exits the Activity, the selection is lost.

Note: To save the selection when the user leaves or pauses the Activity, you must properly save and restore the setting throughout the Activity Lifecycle. To permanently save the selections, even when the Activity process is completely shutdown, you need to save the settings with one of the Data Storage techniques.

To create an AlertDialog with a list of single-choice items like the one shown to the right, use the same code from the previous example, but replace the setItems() method with setSingleChoiceltemsO:

final CharSequence[] items = {"Red", "Green", "Blue"};

AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Pick a color");

builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { Toast.makeText(getApplicationContext(), items[item],

AlertDialog alert = builder.create();

The second parameter in the setSingleChoiceltemsO method is an integer value for the checkedltem, which indicates the zero-based list position of the default selected item. Use "-1" to indicate that no item should be selected by default.

0 0

Post a comment