androidpreferencecheckboxpreferencepreferencefragment

Android: Show/hide preference on checking/unchecking other CheckBoxPreference


Im trying to accomplish such a thing: when I check CheckBoxPreference 'A' the other preference ('B') shows below the A, when I uncheck 'A', preference 'B' hides...

So generally speaking it should work just like dependency but not only enabling/disabling th preference B, but hiding it.

This is what i came up with:

prefA = (CheckBoxPreference)findPreference("preference_A");
prefA.setChecked(false);

prefB = findPreference("preference_B");
category.removePreference(prefB);

prefA.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {

        boolean switchedOn = (Boolean)newValue;
        if (switchedOn)
        {
            Log.d("pref_test", "prefA checked");

            category.addPreference(prefB);
        }
        else
        {
            Log.d("pref_test", "prefA UNchecked");

            prefB = findPreference("preference_B");
            category.removePreference(prefB);   
        }

        return switchedOn;  
    }
});

prefA and prefB have been defined earlier as PreferenceFragment class fields.

The problem is that it works fine only for 2 clicks and my logs say:

prefA checked
prefA UNchecked
prefA UNchecked

Like it was calling onPreferenceChangeListener twice for unchecking (obviously resulting in .removePreference(prefB) method returning null).

Any idea on solving the issue?


Solution

  • Would it not work doing something like this?

    prefA = (CheckBoxPreference)findPreference("preference_A");
    prefA.setChecked(false);
    
    prefB = findPreference("preference_B");
    category.removePreference(prefB);
    
    prefA.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
    
    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
    
            boolean switchedOn = (Boolean)newValue;
            if (switchedOn) {
                 Log.d("pref_test", "prefA checked");
    
                 category.addPreference(prefB);
    
            } else {
                Log.d("pref_test", "prefA UNchecked");
    
                prefB = findPreference("preference_B");
                category.removePreference(prefB);   
            }
    
            return true;  
        }
    });