Remove/hide a preference from the screen

Alex Volovoy picture Alex Volovoy · Feb 10, 2010 · Viewed 73.2k times · Source

I have an activity which extends PreferenceActivity. I'm loading preferences from the xml file. But in some cases i need completely hide one of the preferences from the screen based on my app state. There is a setEnabled method, but it's not exactly what i want. I want to remove that preference from the screen completely. Is it possible ?

Answer

Kavi picture Kavi · Apr 18, 2011

If your Preference is within a PreferenceCategory, you have to do this:

XML:

<PreferenceCategory
    android:key="category_foo"
    android:title="foo">

    <CheckBoxPreference
        android:key="checkPref" />

Java:

CheckBoxPreference mCheckBoxPref = (CheckBoxPreference) findPreference("checkPref");
PreferenceCategory mCategory = (PreferenceCategory) findPreference("category_foo");
mCategory.removePreference(mCheckBoxPref);