How to show and hide preferences on Android dynamically?

后端 未结 6 819
隐瞒了意图╮
隐瞒了意图╮ 2020-12-23 17:46

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 \"w

6条回答
  •  没有蜡笔的小新
    2020-12-23 18:34

    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:

    findPreference("pref_show_extra_stuff").setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                findPreference("pref_extra_stuff_01").setVisible((Boolean) newValue);
                findPreference("pref_extra_stuff_02").setVisible((Boolean) newValue);
                return true;
            }
        });
    

    pref_extra_stuff_01 and pref_extra_stuff_02 are the two preferences that are hidden when pref_show_extra_stuff is toggled.

提交回复
热议问题