Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically populating preferences with checkboxes

Tags:

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.

like image 800
isep Avatar asked May 25 '11 18:05

isep


2 Answers

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); } 
like image 102
inazaruk Avatar answered Oct 16 '22 18:10

inazaruk


Programatically add a preference, with other preferences in xml file: Other solutions didn't work for me because I ALSO had an xml with preferences. I'm not sure all these calls are necessary/redundant, but this works.

onCreate() method, class extends PreferenceActivity:

setContentView(R.layout.preferences); addPreferencesFromResource(R.xml.preferences);  PreferenceScreen pScreen = getPreferenceManager().createPreferenceScreen(this);      CheckBoxPreference cb = new CheckBoxPreference(this); cb.setKey("cb"); cb.setTitle("BLAH"); cb.setOrder(99);        //not working... pScreen.addPreference(cb);  setPreferenceScreen(pScreen); addPreferencesFromResource(R.xml.preferences); 

Sidenote: Since I needed to generate a dynamic checkbox list, it was best suited inside an inner PreferenceScreen. So I created this PreferenceScreen inside the xml, then dynamically generated the checkboxes inside this. This way the ordering didn't matter since all the 'new' dynamica checkboxes were inside this screen.

like image 38
Kevin Avatar answered Oct 16 '22 16:10

Kevin