In my article on AlertDialog with List, I showed you an AlertDialog with a traditional single-choice list.
On touching an item, the dialog will disappear. When you open the dialog again, you wouldn’t be able to know the user’s current choice.
If you want to persist the user’s choice, then you must either use the persistent single-choice list or multiple-choice, if you are interested in more than one item.
In this article, we will see an example for each case.
Main Screen
Let’s start with the main screen. It contains two buttons. One will open the single-choice list and the other will open multiple-choice list. We have assigned the attribute android:onClick to the method that we want to be called as soon as the user presses the button.
welcome.xml:
The list of items
Add the list of static items in strings.xml
strings.xml:
DialogFragment Classes
We will be using a DialogFragment extended class to create the dialog.
In onCreateDialog, we will call AlertDialog.Builder to build the alert dialog. It follows the builder pattern, so you call a method and then keep building on the returned builder object.
If you want to persist the user’s choice, you should set the items using setSingleChoiceItems() or setMultiChoiceItems for multiple-choice. This will create a single-choice list along with radio buttons.
We have three events here. One when the user selects an item. The second when user presses OK button and the third one when user presses Cancel button. Each event has an OnClickListener object assigned to it. When the user selects an item, we will assign the choice to a member variable. When user presses OK, we will persist the choice so next time when user opens the dialog, we will use the persisted choice as the default selection.
Here is the single-choice dialog fragment.
AlertDialogSingleChoiceListExample:
Next is the multiple-choice dialog fragment.
AlertDialogMultipleChoiceListExample:
Main Activity
In the main activity’s onCreate, we create the DialogFragment objects for each case. In openDialogSingleChoice, we show the single-choice dialog. In openDialogMultiChoice, we show the multiple-choice dialog.
MainActivity:
Run the application
Main screen. Let’s press ‘Single Choice’ to open the single-choice list.
Main screen
Select an item and press OK.
Single-Choice Dialog
Multiple-choice list
Multiple-Choice Dialog
After selection, if user re-opens the dialog, the same choice will be shown.
Download the source code
This was an example of AlertDialog with single and multiple-choice persistent list. You can download the source code here: alertDialogWithPersistentList.zip