Strangely, the Android framework does not include a widget which allows multiple selections in Preference Screens. I needed to add one of these for selecting folders to monitor for new media in PicPush and ended up having to implement it myself. If this is something you need for your Android app, following this tutorial will have you up and running in under 5 minutes.
Step 1: Declare a multi-choice preference widget in XML
The first step involves adding the appropriate XML to the file where your preference screen is defined. This can be done as so (You’ll have to change the undefined references to @string constants):
<com.threefiftynice.android.preference.ListPreferenceMultiSelect android:defaultValue="#ALL#"
android:dependency="@string/pref_auto_scan_image"
android:key="@string/pref_upload_buckets_image"
android:title="Image folders to monitor" android:dialogTitle="Image folders to monitor"
android:summary="Specify which folders should be monitored for images"
android:entries="@array/pref_upload_buckets_default_entries"
android:entryValues="@array/pref_upload_buckets_default_values"/>
Step 2: Create Java class which implements the Multiple Choice List Preference
Now, of course, we need a Java class to back this up. The implementation is straightforward. It extends the ListPreference widget so it can inherit all the XML attributes recognized by it. From there, a few key methods are overridden. Source code can be downloaded from here.
Step 2.1: Override onPrepareDialogBuilder (line 44)
onPrepareDialogBuilder is the method responsible for creating the popup dialog which contains all the choices to be displayed. The change from the base class here is simply to set the multi choice entries of the builder rather than the single choice entries. This takes care of the UI.
Step 2.2: Override onDialogClosed (line 69)
When the dialog is closed we need to build a special string to store in the SharedPreferences. The string is made up of the selected entries separated by a special separator string. The separator string i chose is quite weird, it has to be, to avoid conflicts with actual entries.
Step 2.3: Provide a static convenience method for parsing the stored value into a String array (line 62)
When a client reads back the stored value from the SharedPreferences it wont be very useful unless it can be parsed. This can be delegated to our custom implementation via a static method called parseStoredValue. This convenience method returns a String array which contains the user’s choices.
Step 3: You’re Done! Run the code!
Following the above steps should have you in good shape to get up and running. I implemented this code a few days ago, and am writing this tutorial from memory so i may have missed a few small details, however the main bones of the implementation is definitely contained here. Any problems/questions? Leave a comment below.