I have CheckBoxPreference and 2 others: one is Edit Test Pref. and another is ListBox Pref. How I can enable list box pref and disable edit text pref. when CheckBoxPreference is turned on?
4 Answers
As a variant, it's possible to put the "dependency" into the ListBoxPref.
<PreferenceCategory
android:key="key1"
android:title="@string/title1">
<SwitchPreference
android:key="parents"
android:summaryOff="@string/do_smthng"
android:summaryOn="@string/do_smthng"
android:switchTextOff="@string/i_am_sleeping"
android:switchTextOn="@string/i_have_free_time" />
<CheckBoxPreference
android:key="baby"
android:dependency="parents"
android:title="@string/basic_habbits"
android:summaryOff="@string/play_with_parents"
android:summaryOn="@string/play_with_parents"
android:defaultValue="true" />
</PreferenceCategory>
Basically, baby can't play with parents when they are sleeping =)
-
You are awesome sir! – Mohamed Feb 20 '17 at 23:26
-
Exactly what I was looking for... I had disabled the use in my code, but needed to show the user that they are disabled so they can turn it on. – ShadowZzz Mar 28 '17 at 17:48
Seems it's duplicate of this question
You can override public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String key)
and when it get called with key.equals(<Your key for setting>)
do something like:
boolean isEnabled = sharedPreferences.getBoolean(key, true);
getPreferenceScreen().findPreference("list box preference key").setEnabled(isEnabled);
getPreferenceScreen().findPreference("list box preference key").setEnabled(!isEnabled);
Also, do the same in onCreate()
to have Your preferences screen proper initial setup.
You can get the checkbox value. And then, to enable/disable the preferences, you can use pref.setEnabled(false);
To enable, just use the same function and put the true value.

- 939
- 1
- 10
- 13
Just to simplify the answer from Sergio,
android:dependency="keyOfParent"
This makes the item dependent on the parent item, may need to be a switch.
Also adding a listener to the onSharedPreferenceChanged works, sometimes.. it sometimes doesn't work as desired ( not sure why )
Add
public class YourClass extends Whatever implements SharedPreferences.OnSharedPreferenceChangeListener
Then after OnCreate()
@Override
public void onSharedPreferenceChanged (SharedPreferences p1, String p2)
{
if (Your Arguments)
{
// getPreferenceScreen().findPreference("pref_key").setEnabled(false);
}
}

- 588
- 6
- 12