SoulRayder
SoulRayder

Reputation: 5166

How to hide dependent Edittextpreferences when a Checkboxpreference is checked?

I have a CheckBoxPreference and two EditTextPreferences which are dependent on the CheckBoxPreference (all defined in an xml file and all three together inside a single PreferenceScreen).

My question is this: How to hide and redisplay those two EditTextPreferences when the user unchecks and checks the Checkboxpreference respectively?

Currently I am just able to enable/disable them by adding the android:dependency attribute to them.

Solutions to do so in java or in xml will be appreciated. :)

Upvotes: 2

Views: 732

Answers (1)

CurlyPaul
CurlyPaul

Reputation: 1158

I'm not aware of anyway to do this through xml, which always my preferred choice. But this java solution should work.

CheckBoxPreference chkPref = (CheckBoxPreference)findPreference("myCheckPref");
EditTextPreference editPref1 = (EditTextPreference)findPreference("myEditCheckPref");
PreferenceGroup editTextParent = getParent(editPref1);

chkPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener(){

public boolean onPreferenceChange(Preference pref, Object value)
{
   if(value)
      editTextParent.addPreference(editPref1);
   else
      editTextParent.removePreference(editPref1);

return true;
}

});

As there is no in built way to find the parent group of a parent, you will also have to define these functions:

private PreferenceGroup getParent(Preference preference)
{
    return getParent(getPreferenceScreen(), preference);
}

private PreferenceGroup getParent(PreferenceGroup root, Preference preference)
{
    for (int i = 0; i < root.getPreferenceCount(); i++)
    {
        Preference p = root.getPreference(i);
        if (p == preference)
          return root;
       if (PreferenceGroup.class.isInstance(p))
       {
        PreferenceGroup parent = getParent((PreferenceGroup)p, preference);
        if (parent != null)
            return parent;
    }
}
  return null;
} 

Upvotes: 1

Related Questions