Set a list of items to be displayed in the dialog as the content, you will be notified of the selected item via the supplied listener. The list will have a check mark displayed to the right of the text for the checked item. Clicking on an item in the list will not dismiss the dialog. Clicking on a button will dismiss the dialog.
Parameters:
items - the items to be displayed.
checked -Item specifies which item is checked. If -1 no items are checked.
listener - notified when an item on the list is selected. The dialog will not be dismissed when an item is clicked. It will only be dismissed if clicked on a button, if no buttons are supplied it's up to the user to dismiss the dialog.
Returns: This Builder object to allow for chaining of calls to set methods
1. Create an AlertDialog with Supplied Arguments
2. Initialize a CharSequence Array
3. Add the line below to the imports section.
import android.content.DialogInterface;
4. After your AlertDialog.Builder is instantiated in step 1, add the following code to set a list of items with a radio button to an AlertDialog. This will display the myCharSequence array in the list. Once you select an item, the dialog box does NOT automatically close. You may wish to Add a Positive Button to close the AlertDialog or add dismiss, as in the example below. The 0 signifies that the first item in the list will be selected by default. To have non selected, change the 0 to -1.
myAlertDialogBuilder.setSingleChoiceItems(myCharSequence, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// To test, Add a Toast with a context of getBaseContext() and a message such as
// "You selected "+ myCharSequence[which] //<- this will display the item selected
//once selected, the dialog box does NOT automatically close.
//To close the AlertDialog, you could Add a dismiss
}
});
5. Compile and run!
User selects the first option |
Next Recommended Article: setMultiChoiceItems - How to Add a Multiple Choice List of Items to an AlertDialog.Builder
http://developer.android.com/reference/android/app/AlertDialog.Builder.html#setSingleChoiceItems(java.lang.CharSequence[], int, android.content.DialogInterface.OnClickListener)
http://stackoverflow.com/questions/6421196/how-to-dismiss-alertdialog-with-radio-buttons-in-android-sdk