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 setMultiChoiceItemsi) and setSingleChoiceItemsO 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 setSingleChoiceItemsO:

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 setSingleChoiceItemsO 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.

ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "",

The first parameter is the application Context, the second is a title for the dialog (left empty), the third is the message, and the last parameter is whether the progress is indeterminate (this is only relevant when creating a progress bar, which is discussed in the next section).

The default style of a progress dialog is the spinning wheel. If you want to create a progress bar that shows the loading progress with granularity, some more code is required, as discussed in the next section.

0 0

Post a comment