I am creating several Color Picker preferences (extended from Preference) in the onCreate method of my Preference Fragment.
The colorpickers describe the current design that is active. So when the user picks a new design (in the same PreferenceFragment) all color pickers have to change according to the new design.
For this I am getting the new color values of the current design and rebuild the PreferenceFragment
public static void RebuildSettings() {
colorFieldList = GetNewColorFields();
if (mPrefsFragment != null) {
mPrefsFragment.onDestroy();
mPrefsFragment.onCreate(null);
} else Log.i(Patterns.TAG, "mPrefsFragment = null");
}
In the onCreate method of my Preference Fragment I then recreate the color fields from colorFieldList (with the colors from new design) like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
[...]
PreferenceCategory colorSettings = (PreferenceCategory) findPreference("prefCat_ColorSettings");
for (int i = 0; i < colorFieldList.size(); i++) {
AmbilWarnaPreference colorPicker = new AmbilWarnaPreference(getActivity(), null);
colorPicker.forceSetValue(colorFieldList.get(i).color);
colorPicker.setTitle(colorFieldList.get(i).name);
colorPicker.setSummary("Set color in " + colorFieldList.get(i).name);
colorPicker.setKey("colorField" + colorFieldList.get(i).index);
colorPicker.setOnPreferenceChangeListener(colorListener);
if (colorSettings != null)
colorSettings.addPreference(colorPicker);
}
[...]
}
Now I can change the designs and the color fields will update fine according to the new design BUT only when I have not changed any color picker field yet. The fields change like they are supposed to but as soon as I change a color field / pick a new color, this field forever stays the color I chose, although I rebuild the settings completely every time the design is changed!
What am I missing? Why are the colors updating as long as no value is saved to SharedPreferences (?) but not after?
I guess android always grabs the value of the color picker from shared preferences once it has been set, but how can I overwrite it in OnCreate to depict the colors from the chosen design?
Your help is highly appreciated! Thanks!
I figured it out: Like I assumed the problem was that the items always received the default values for their specific key.
To overwrite this behaviour I had to call Apply() (commit would also work I guess) on the editor in the onCreate() method of my preference fragment like this:
getPreferenceManager().getSharedPreferences().edit().putInt("colorField" + colorFieldList.get(i).index, colorFieldList.get(i).color).apply();
(I did this in the loop I posted above, so every color preference was assigned to a new color on creation with an overwritten preference value)