Wednesday, 21 August 2013

Correctly creates a new AlertDialog with Single and multiple choice List

There are several way to implement an AlertDialog with a Single choice list. The follow one seems pretty good:

private AlertDialog createNationalityAlertDialog() {
    // Creates the alert dialog
    final CharSequence[] content = {"a", "b", "c", "d"};

    AlertDialog alertDialog =  new AlertDialog.Builder(context)
        .setTitle(R.string.alert_dialog_title)
        .setSingleChoiceItems(content, itemSelected, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
        .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            int selecctedItemPosition = ((AlertDialog)dialog).getListView().getCheckedItemPosition();
                // Do something with the position
            }
        })
        .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                /* User clicked No so do some stuff */
            }
        })
       .create();
    return alertDialog;
}

The main reason why the position is not set on the onClick of setSingleChoiceItems is because the user can press the cancel button later, so the decision could not be de definitive one.

For the multiple choice lists, use the method getCheckedItemPositions() instead, it will return an SparseBooleanArray, which is an map of the all the selected positions with a bool value.

.setPositiveButton(R.string.alert_dialog_ok,
        new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        /* User clicked Yes so do some stuff */
    SparseBooleanArray positions = ((AlertDialog)dialog).getListView().getCheckedItemPositions();
    if (positions != null) {
    for (int i = 0; i < positions.size(); i++) {
    final boolean isChecked = positions.valueAt(i);
    if (isChecked) {
        final int position = positions.keyAt(i);
    // Do something with the position
    }
    }
    }
    }
})

Source and inspiration:
StackOverflow - Android dialog single choice get radio selected

No comments:

Post a Comment