How to show and hide preferences on Android dynamically? How to show and hide preferences on Android dynamically? android android

How to show and hide preferences on Android dynamically?


From a PreferenceActivity call

Preference somePreference = findPreference(SOME_PREFERENCE_KEY);PreferenceScreen preferenceScreen = getPreferenceScreen();preferenceScreen.removePreference(somePreference);

you can later call:

preferenceScreen.addPreference(somePreference);

The only a little bit tricky part is getting the order correct when adding back in. Look at PreferenceScreen documentation, particularly it's base class, PreferenceGroup for details.

Note: The above will only work for immediate children of a PreferenceScreen. If there is a PreferenceCategory in between, you need to remove the preference from its parent PreferenceCategory, not the PreferenceScreen. First to ensure the PreferenceCategory has an android:key attribute set in the XML file. Then:

Preference somePreference = findPreference(SOME_PREFERENCE_KEY);PreferenceCategory preferenceCategory = (PreferenceCategory) findPreference(SOME_PREFERENCE_CATEGORY_KEY);preferenceCategory.removePreference(somePreference);

and:

preferenceCategory.addPreference(somePreference);


Not exactly hiding/showing but if you only want disabling/enabling preference depending on another preference you can specify android:dependency="preferenceKey" or Preference.setDependency(String)

Example from developer.android.com:

<?xml version="1.0" encoding="utf-8"?><PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">    <CheckBoxPreference        android:key="pref_sync"        android:title="@string/pref_sync"        android:summary="@string/pref_sync_summ"        android:defaultValue="true" />    <ListPreference        android:dependency="pref_sync"        android:key="pref_syncConnectionType"        android:title="@string/pref_syncConnectionType"        android:dialogTitle="@string/pref_syncConnectionType"        android:entries="@array/pref_syncConnectionTypes_entries"        android:entryValues="@array/pref_syncConnectionTypes_values"        android:defaultValue="@string/pref_syncConnectionTypes_default" /></PreferenceScreen>


I recommend using V7 preference, it has setVisible() method. But I have not tried it yet.