Create new preference and persist it?
I'm trying to create a new CheckBoxPreference under a PreferenceGroup for displaying tags. The plan is to add the tags with code like this:
for(Tag t : tags) {
pref = new CheckBoxPreference(FoodhunterCredentials.this);
boolean isChecked = wasChecked(t.getName());
pref.setTitle(t.getName());
pref.setSummary(t.getDescription());
pref.setChecked(isChecked);
pref.setPersistent(true);
Log.d("Credentials", String.format("Adding checkbox %s -开发者_如何学C%schecked", t, isChecked ? " " : " not "));
tagsGroup.addPreference(pref);
}
But after closing the activity the new checkboxes are gone. Is there a way for persisting the newly created preferences? To be clear: This is not about storing a new value in a defined preference, this is about storing a new created preference.
You can use DB to store all your tags (this is preferable).
Or, if you don't want to use DB for some reason, you can hack with SharedPreferneces
in a next way:
- Create empty string preference named "tags" (this should not be visible in your PreferenceActivity).
- When user adds new tag, your will add tag name to "tags" string preference and save it.
For example, your "tags" string may look like "java;android;helper;europe". You'll need to make duplication checks and parsing yourself. Of cause you'll need to automatically populate your PreferenceScreen in onCreate()
method with CheckBoxPreference
for each tag, but you already know how to do it.
Yes, and in API level 11 (Android 3.0) and higher you can use String Sets in SharedPrefernces
. See getStringSet
and putStringSet
for more details.
You are not able to modify the XML layout files problematically. You can store the fact that you have an extra check-box in the SharedPreferences or Database but there isn't a super-clean way of doing what you want.
精彩评论