Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove PreferenceCategory programmatically?

I need to remove a PreferenceCategory programmatically. I could remove the individual preferences with the following code but I need to remove (disable) whole PreferenceCategory as well.

PreferenceScreen preferenceScreen = getPreferenceScreen(); EditTextPreference etp = (EditTextPreference) preferenceScreen.findPreference("pref22"); ((PreferenceGroup) findPreference("prefcat")).removePreference(etp); 

Edit: Here's the working code for a PreferenceCategory "prefcat" and a child preference "pref22":

PreferenceScreen preferenceScreen = getPreferenceScreen(); EditTextPreference etp = (EditTextPreference) preferenceScreen.findPreference("pref22");  PreferenceGroup preferenceGroup = (PreferenceGroup) findPreference("prefcat"); if (preferenceGroup != null) {     preferenceGroup.removePreference(etp);     preferenceScreen.removePreference(preferenceGroup); } 
like image 860
Harald Wilhelm Avatar asked Apr 09 '11 14:04

Harald Wilhelm


2 Answers

you can hide a category by getting reference to PreferenceScreen:

I your xml :

<PreferenceScreen  xmlns:android="http://schemas.android.com/apk/res/android"  android:key="@string/preferenceScreen">  //set all you values //Preference, PreferenceCategory and/or CheckBoxPreference  </PreferenceScreen> 

in you string.xml : don't forgot to set this new string

 <string name="preferenceScreen" translatable="false">preferenceScreen</string> 

in you code:

preferenceScreen = (PreferenceScreen) findPreference(getResources().getString(R.string.preferenceScreen)); 

and then remove the category from your PreferenceScreen :

myCategory = (PreferenceCategory) findPreference(getResources().getString(R.string.my_category)); myPreferenceScreen.removePreference(myCategory); 
like image 90
douarbou Avatar answered Sep 30 '22 14:09

douarbou


Don't load the PreferenceCategory in the first place.

If you are defining your preferences in Java, don't create the PreferenceCategory.

If you are defining your preferences in XML, use three XML files:

  1. One for stuff before this magic category
  2. One for the magic category
  3. One for stuff after this magic category

In situations where you want the category, load all three XML files. In situations where you do not want the category, load only the first and third XML files.

like image 27
CommonsWare Avatar answered Sep 30 '22 15:09

CommonsWare