How to edit a ListPreference value from java code in Android

Sephy picture Sephy · Jul 19, 2010 · Viewed 8.7k times · Source

I know how to change the value of a CheckBoxPreference, but I can't get it to work for a ListPreference.

Here is how my preference screen is built:

  • one CheckBox for the default
  • A ListPreference to select a color other than the default.

The ListPreference is defined with the key "titleColor", as follows :

CharSequence[] entries = { "Dark grey", "Light grey", "Light red", "Red" };
CharSequence[] entryValues = { "#4c4c4c", "#b5b5b5", "#ab6a68", "#962622" };
final ListPreference color = (ListPreference) findPreference("titleColor");
color.setEntries(entries);
color.setEntryValues(entryValues);

Now, when I select a color I do this:

color.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            System.out.println("In the onClick method");
            System.out.println("change title color");
            Editor editor2 = defaultColor.getEditor();
            editor2.putBoolean("defaultColor", false);
            editor2.commit();
            return true;
        }

    });

And this seems to work, though I'm not sure to do this properly.

Now I have been trying to do something similar when I select the default color, but I can't get the list to either uncheck everything OR check a color that would be the default.

Any idea?

Answer

Macarse picture Macarse · Jul 19, 2010

In the case of the CheckBox:

If you had a default color CheckBox it would be fixed using android:dependency, but since you don't have it, I guess that's the only way.

Related with the ListPreference, is quite similar:

ListPreference lp = (ListPreference)findPreference("listPreference_key");
lp.setValue("");

You can check the docs to know which methods are available.