Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - How to hide a control in PreferenceFragment

Tags:

android

In my preferences UI, I need to hide a preference based on certain conditions.

public class MyFragment extends PreferenceFragment {
  public void onCreate(Bundle state) {
    addPreferencesFromResource(...);
    ListPreference myList = (ListPreference) findPreference("myid");

    ...
    if (condition) {
      // hide myList
    }
 }

}

I cannot seem to find any method either on ListPreference or on PreferenceFragment to hide it from being shown in the UI. Would appreciate if you can point me in the right direction.

like image 869
Peter Avatar asked Jan 31 '14 01:01

Peter


2 Answers

After much debugging, turns out it was quite simple. Here is what you need to do:

First, obtain the PreferenceCategory the item belongs to. Next, just call removePreference on it.

 PreferenceCategory myCategory = (PreferenceCategory) findPreference("myPrefCategory");
 myCategory.removePreference(myList);
like image 144
Peter Avatar answered Oct 07 '22 09:10

Peter


For those wondering how to remove item that has no parent category - you should name your root like this:

<PreferenceScreen
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:key="root_preferences">
<PreferenceCategory
        android:title="Developer tools"
        android:key="dev_tools_category">

Then for example:

if (!BuildConfig.DEBUG) {
    PreferenceScreen rootPreferences = (PreferenceScreen) findPreference("root_preferences");
    PreferenceCategory devCategory = (PreferenceCategory) findPreference("dev_tools_category");
    rootPreferences.removePreference(devCategory);
}

In example above "dev_tools_category" could be any preference widget or like I showed - a category.

like image 2
wtk Avatar answered Oct 07 '22 07:10

wtk