Dynamic ListPreference in android

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);

Leave a Comment