Programmatically populating preferences with checkboxes

isep picture isep · May 25, 2011 · Viewed 12.7k times · Source

In my setting page I have a preference which fetches a list of toggle-able settings that I wanted to display as individual checkbox preferences.

I know that preferences.xml supports generating lists of preferences (looking at wi-fi settings page) but ListPreference only allows you to select one from the list.

I've been searching for how to generate preferences programmatically but have only managed to find how to change attributes of preferences that are already in the XML.

Answer

inazaruk picture inazaruk · May 25, 2011

Here is a short example (assuming you are extending PreferenceActivity):

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    PreferenceScreen screen = getPreferenceManager().createPreferenceScreen(this);

    PreferenceCategory category = new PreferenceCategory(this);
    category.setTitle("category name");

    screen.addPreference(category);

    CheckBoxPreference checkBoxPref = new CheckBoxPreference(this);
    checkBoxPref.setTitle("title");
    checkBoxPref.setSummary("summary");
    checkBoxPref.setChecked(true);

    category.addPreference(checkBoxPref);
    setPreferenceScreen(screen);
}