6

Is possible to hide a preference in a PreferenceScreen? I don't need to disable it, it must be invisible (sometimes)

Important: I need to keep the min API level 7+

Lukas Knuth
  • 25,449
  • 15
  • 83
  • 111
Addev
  • 31,819
  • 51
  • 183
  • 302

5 Answers5

19

If your logout button (Preference) is in the PreferenceScreen, do this:

PreferenceScreen screen = getPreferenceScreen();
Preference logout = findPreference("logout");
if(screen != null && logout != null)
  screen.removePreference(logout);

Else if your logout button (Preference) is in a PreferenceCategory (which is inside a PreferenceScreen), do this:

PreferenceCategory category = (PreferenceCategory) findPreference("category_name");
Preference logout = findPrefence("logout");
if(category != null && logout != null)
  category.removePreference(logout);

You can put whatever your preferences name is, this is for example for a logout preference, if you have another Preference (eg CheckBoxPreference) you need to cast that specific Preference before findPreference.

sais
  • 803
  • 6
  • 15
Carnal
  • 21,744
  • 6
  • 60
  • 75
4

Something like that should works:

Preference p = findPreference("your_preference_key");
getPreferenceScreen().removePreference(p);
rciovati
  • 27,603
  • 6
  • 82
  • 101
1

PreferenceScreen scr = getPreferenceScreen();

if(scr!=null)

     scr.removePreference(findPreference("preferenceKey"));
Shiv Buyya
  • 3,770
  • 2
  • 30
  • 25
0

If you use Support Library v7 Preference, you can use the setVisible method. It does exactly what you need.

guillaume-tgl
  • 2,749
  • 3
  • 23
  • 30
0

You can now do this directly in xml with the AppCompat library.

See https://stackoverflow.com/a/54154665/114549

aaronvargas
  • 12,189
  • 3
  • 52
  • 52