Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android CheckBoxPreference: how to disable and enable other preferences on preference change

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?

like image 518
vmg Avatar asked Oct 13 '11 08:10

vmg


2 Answers

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);
      }
     }
like image 181
Empire of E Avatar answered Sep 19 '22 11:09

Empire of E


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

like image 32
Sergio Avatar answered Sep 22 '22 11:09

Sergio