I have a ListPreference
which look something like this:
<ListPreference android:title="Choose item" android:summary="..." android:key="itemList" android:defaultValue="item1" android:entries="@array/items" android:entryValues="@array/itemValues" />
Then, I have another preference which should only be enabled if "item3" is selected in the ListPreference
.
Can I somehow accomplish this with android:dependency
? Something like android:dependency="itemList:item3"
Thanks!
A Preference that displays a list of entries as a dialog. This preference will store a string into the SharedPreferences. This string will be the value from the setEntryValues(java. lang.
preference. Kotlin |Java. The Preference library allows you to build interactive settings screens, without needing to handle interacting with device storage or managing the user interface.
The only way you can do something like this is programmaticly.
You'd have to set up an change listener on the ListPreference and then enable/disable the other one.
itemList = (ListPreference)findPreference("itemList"); itemList2 = (ListPreference)findPreference("itemList2"); itemList.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String val = newValue.toString(); int index = itemList.findIndexOfValue(val); if(index==3) itemList2.setEnabled(true); else itemList2.setEnabled(false); return true; } });
If I were you I wouldn't even show the second preference if the first isn't set properly. To do that you have to declare the preference manually (not in the XML) and add/remove it instead of enabling/disabling.
Now isn't this the bestest answer you've ever seen?!
Emmanuel
Subclass ListPreference
class, and override setValue
and shouldDisableDependence
methods.
setValue
will call notifyDependencyChange(shouldDisableDependents())
after super.setValue
when the value is actually changed.
shouldDisableDependence
returns false only if the current value is item3, or any other desired value stored in mDepedenceValue
.
@Override public void setValue(String value) { String mOldValue = getValue(); super.setValue(value); if (!value.equals(mOldValue)) { notifyDependencyChange(shouldDisableDependents()); } } @Override public boolean shouldDisableDependents() { boolean shouldDisableDependents = super.shouldDisableDependents(); String value = getValue(); return shouldDisableDependents || value == null || !value.equals(mDepedenceValue); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With