I'm setting out to create a settings activity for my app. I've defined a PreferenceActivity
with a nice layout including a ListPreference
object for the user to select a bluetooth device. I'm having trouble dynamically populating the list.
I would like to populate ListPreference
with values from an array adapter (which I'll create and populate with relevant bluetooth device names).
If this were a spinner View, I could just call setAdapter()
. However with the ListPreference
object I can't figure out how to attach an adapter (findviewByID
won't cast from View To ListPreference
, so I can't even get a handle to the object).
I would like to attach an adapter and then populate the adapter with values, which in turn would populate the ListPreference
with values.
ListPreference
doesn't work with adapters, it works with strings. SeesetEntries()
andsetEntryValues()
To get at your
ListPreference
, callfindPreference()
on yourPreferenceActivity
. Cast thePreference
you get back toListPreference
.Just an Update to this in case someone else comes along, ge0rg answer works but changed it a little to take in consideration of multiple preferences and not just the bluetooth one and also if they dont have any paired devices set up so you dont get an error with a null array.
`Hope this helps someone...oh and this is put under the onCreate method for the preference activity
Another way would be to override onPrepareDialogBuilder of ListPreference and to initialize setSingleChoiceItems of AlertDialog.Builder directly with your adapter:
If you look at the Android sources, you'll find that onPrepareDialogBuilder() does call:
with those entry arrays. To make ListPreference use some adapter (e.g. ArrayAdaper, CursorAdapter), you just need to call:
instead.
This way ListPreference will operate on the adapter directly and you don't need to copy the data from the adapter to put them into the entries arrays.
Find a working sample here.
For the special case of a list of bluetooth devices, you can use the following class:
It can be involved directly from your prefs XML to store the MAC as a prefs string: