Is there a way to dynamically show and hide preferences? In my case, I have a checkbox preference that would disable or enable one of 2 preference groups ("with-" and "without-handicap" groups). While this would be the ideal GUI in a desktop environment, the "with-handicap" takes up nearly the whole screen, while the other, "without-handicap" takes up only a small portion of the screen.
Rather than showing both groups at the same time, I'd like to show only one of them at a time, and dynamically show or hide the 2 groups when the checkbox changes. Is there a way to do this?
For hiding preferences dynamically, I created an if-condition upon whose value I decide whether I want the pref to show or not. To do the actual hiding, I have been using:
The tricky part is to make it visible again. There is no direct way to do it except to recreate the layout. If the value of the if-condition is false, which means the pref should be visible, then the code to hide the pref will never be executed, thus resulting in a visible pref. Here is how to recreate the layout (in my case, I am extending a PreferencesListFragment):
I hope that was helpful.
I recommend using V7 preference, it has
setVisible()
method. But I have not tried it yet.From a PreferenceActivity call
you can later call:
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 aPreferenceCategory
in between, you need to remove the preference from its parentPreferenceCategory
, not thePreferenceScreen
. First to ensure thePreferenceCategory
has anandroid:key
attribute set in the XML file. Then:and:
I needed something similar: toggling a switch to hide or show two extra preferences. Check out the sample app from Android-Support-Preference-V7-Fix which bring some new preference types and fixes some issues from the official library. There's an example there to toggle a checkbox to show or hide a preference category.
In the fragment that extends PreferenceFragmentCompatDividers, you could use something like:
pref_extra_stuff_01 and pref_extra_stuff_02 are the two preferences that are hidden when pref_show_extra_stuff is toggled.
Not exactly hiding/showing but if you only want disabling/enabling preference depending on another preference you can specify
android:dependency="preferenceKey"
orPreference.setDependency(String)
Example from developer.android.com:
If you want to implement the hiding of the preference completely in the Preference, here is one example. Does not allow to make it visible again, though.