Dynamic ListPreference in android

kkk picture kkk · Mar 21, 2011 · Viewed 35.5k times · Source

How to generate dynamic listPreference in android? I want to get all wifi access points and make a list using in preference Activity(i.e. make a list using listpreference). How to do this?

Answer

Philio picture Philio · Mar 21, 2011

Every XML element in Android can be created programmatically as the element name is also a Java class. Hence you can create a ListPreference in code:

CharSequence[] entries = { "One", "Two", "Three" };
CharSequence[] entryValues = { "1", "2", "3" };
ListPreference lp = new ListPreference(this);
lp.setEntries(entries);
lp.setEntryValues(entryValues);

You could alternatively create it in XML then add the entries/entry values in code:

CharSequence[] entries = { "One", "Two", "Three" };
CharSequence[] entryValues = { "1", "2", "3" };
ListPreference lp = (ListPreference)findPreference("list_key_as_defined_in_xml");
lp.setEntries(entries);
lp.setEntryValues(entryValues);