15

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?

vmg
  • 9,920
  • 13
  • 61
  • 90

4 Answers4

37

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 =)

serv-inc
  • 35,772
  • 9
  • 166
  • 188
Sergio
  • 558
  • 5
  • 10
35

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.

Community
  • 1
  • 1
sandrstar
  • 12,503
  • 8
  • 58
  • 65
4

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.

Sarah Sakamoto
  • 939
  • 1
  • 10
  • 13
3

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);
      }
     }
Empire of E
  • 588
  • 6
  • 12