简体   繁体   中英

How to edit a ListPreference value from java code in Android

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM