简体   繁体   中英

Hide item in Android preferences menu

my Application has a Preferences menu. there are 2 checkbox: "Enable Music", and "Show Hints". What I want is, There is Music List will show if check "Enable Music", else Music list will not enable. My code is:

boolean OPT_MUSIC_DEF = true;
protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      addPreferencesFromResource(R.xml.settings);
      if (!PreferenceManager.getDefaultSharedPreferences(this).getBoolean(OPT_MUSIC, OPT_MUSIC_DEF)){
                Preference list = findPreference("music_list");
                list.setEnabled(false);
         }
}

There is no error, but it work incorrect. When I unCheck "Enable Music" Music List did not hide right away, I must back and go to menu again to see Music List is hide. Any way to make it hidden directly after uncheck "Enable Music" item? thank for help me!

There is built in functionality to do exactly what you're trying to do. In your preferences.xml file set the dependency for the music_list preference to depend on the music_enable preference.

For example:

    <android.preference.CheckBoxPreference
        android:key="music_enable"
        android:defaultValue="false"
        android:title="Enable Music"
        />

    <android.preference.ListPreference
        android:key="music_list"
        ...
        android:dependency="music_enable"
        />

Whenever the user checks the "music_enable" check box the "music_list" will be enabled; when they uncheck the "music_enable" check box the "music_list" will be disabled.

If you want to force refresh the appearance of your preference, just do:

Preference myPref = findPreference("mypref");
myPref.setDefaultValue((int)(Math.random()*1000); // you can also backup the value before and reset it after if you need to keep a default value

Not the perfect solution, but it will surely force Android to refresh your preferences.

BTW, I tried Paul-Jan solution but unluckily it didn't work, it seems that onContentChanged() will just do nothing if no value is changed.

确保禁用首选项后立即调用onContentChanged()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM