Dynamically create CheckBoxPreferences

askilondz picture askilondz · Jun 8, 2011 · Viewed 13.2k times · Source

I am currently building out a list of rows with checkboxes dynamically using content from a web service. However, this ListView will need to do pretty much what a PreferenceActivity would accomplish.

I don't know the number of rows as the content is dynamic so I can't create each CheckBoxPreference in XML. How do I go about building a PreferenceActivity that will display an unknown number rows with a CheckBoxPreference dynamically?

Answer

plowman picture plowman · Jul 2, 2011

I think you're looking for something like this:

public class MyPreferenceActivity extends PreferenceActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.my_preference_activity);

        //fetch the item where you wish to insert the CheckBoxPreference, in this case a PreferenceCategory with key "targetCategory"
        PreferenceCategory targetCategory = (PreferenceCategory)findPreference("targetCategory");

        //create one check box for each setting you need
        CheckBoxPreference checkBoxPreference = new CheckBoxPreference(this);
        //make sure each key is unique  
        checkBoxPreference.setKey("keyName");
        checkBoxPreference.setChecked(true);

        targetCategory.addPreference(checkBoxPreference);
    }
}