148

I have an activity which extends PreferenceActivity. I'm loading preferences from the xml file. But in some cases i need completely hide one of the preferences from the screen based on my app state. There is a setEnabled method, but it's not exactly what i want. I want to remove that preference from the screen completely. Is it possible ?

Herry
  • 7,037
  • 7
  • 50
  • 80
Alex Volovoy
  • 67,778
  • 13
  • 73
  • 54

16 Answers16

219

If your Preference is within a PreferenceCategory, you have to do this:

XML:

<PreferenceCategory
    android:key="category_foo"
    android:title="foo">

    <CheckBoxPreference
        android:key="checkPref" />

Java:

CheckBoxPreference mCheckBoxPref = (CheckBoxPreference) findPreference("checkPref");
PreferenceCategory mCategory = (PreferenceCategory) findPreference("category_foo");
mCategory.removePreference(mCheckBoxPref);
JJD
  • 50,076
  • 60
  • 203
  • 339
Kavi
  • 3,880
  • 2
  • 26
  • 23
  • 6
    To be fair, the above answer does say that you need the parent `PreferenceCategory`. – matt Jun 06 '14 at 00:09
178

Yes, if you have a reference to both the Preference, and its parent (a PreferenceCategory, or PreferenceScreen)

myPreferenceScreen.removePreference(myPreference);
darrenp
  • 4,265
  • 2
  • 26
  • 22
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
54

In the case where the Preference is a direct child of the preference screen, here is some stand-alone code:

PreferenceScreen screen = getPreferenceScreen();
Preference pref = getPreferenceManager().findPreference("mypreference");
screen.removePreference(pref);
1''
  • 26,823
  • 32
  • 143
  • 200
  • 4
    This wont work if the preference is located inside category. you have to `findPreference` for the category, and remove the preference from the category – MBH Sep 10 '17 at 14:34
  • 1
    @MBH: Thanks for mentioning that caveat! – 1'' Sep 11 '17 at 03:49
21

If you are using PreferenceFragmentCompat you can set the visiblity in xml.

The preferences in your xml will be converted to AppCompat versions automatically. You can then use the 'app:isPreferenceVisible' attribute in your xml

preferences.xml

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <CheckBoxPreference
        android:defaultValue="false"
        android:key="show.navigation"
        android:title="Show navigation"
        app:isPreferenceVisible="false" />

...

The attribute is documented at https://developer.android.com/guide/topics/ui/settings/components-and-attributes

Adding PreferenceFragmentCompat is documented at https://developer.android.com/guide/topics/ui/settings/#inflate_the_hierarchy

Example:

public class MySettingsActivity extends AppCompatActivity {

    public static class MySettingsFragment extends PreferenceFragmentCompat {
        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            setPreferencesFromResource(R.xml.preferences, rootKey);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.settings_container, new MySettingsFragment())
                .commit();
    }
} 
aaronvargas
  • 12,189
  • 3
  • 52
  • 52
9

If you want something that will dynamically change the prefs for example on a SwitchPreference, I have found the best way is to put all my sub options into two category containers. Initially you'll have everything shown, then you just remove the bits you don't want. The clever bit, is you just trigger recreate when something changes and then you don't have to manually create anything or worry about putting things back in in the correct order.

protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  addPreferencesFromResource(R.xml.preferences);
  PreferenceCategory prefCatOne= (PreferenceCategory)findPreference("prefCatOne");
  PreferenceCategory prefCatTwo= (PreferenceCategory)findPreference("prefCatTwo");
  SwitchPreference mySwitchPref= (SwitchPreference)findPreference("mySwitchPref");
  PreferenceScreen screen = getPreferenceScreen();
  if (mySwitchPref.isChecked()) {
    screen.removePreference(prefCatOne);
  } else {
    screen.removePreference(prefCatTwo);
  }
}

public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
    if (key.equals("mySwitchPref")) {
        this.recreate();
    }
}

The only downside that I can see with this, is there is a flash as the screen is recreated from scratch.

James
  • 371
  • 4
  • 3
  • The case does not work, at least not in 22. But changing it to a Preference (even though it's a grouping of preferences) does work. – Rob Apr 02 '15 at 16:21
  • Rob, I just tested the above code in an API22 AVD and it's working just fine. Make sure your preference XML content matches your code. For the above example the SwitchPreference can be anywhere, but you need the PreferenceCategorys to be direct children of the PreferenceScreen. – James Apr 02 '15 at 20:46
  • I just got the Category as a Preference, no cast, and removed it. Worked. – Rob Apr 03 '15 at 01:14
8

In your XML file:

<PreferenceScreen 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:key="preferenceScreen">

    <PreferenceCategory
        android:key="personalisation"
        android:title="your title here">

        <ThemedPreference
            android:key="animation" />

</PreferenceScreen>

In your code:

PreferenceScreen pPreferenceScreen = (PreferenceScreen) findPreference("preferenceScreen");

PreferenceCategory pCategory = (PreferenceCategory) findPreference("personalisation");
ThemedPreference pThemePref = (ThemedPreference) findPreference("animation");

pPreferenceScreen.removePreference(pCategory); //remove category
pCategory.removePreference(pThemePref);   // remove preference
JJD
  • 50,076
  • 60
  • 203
  • 339
user3165739
  • 166
  • 2
  • 3
7

I recommend using v7 preference, it has setVisible() method. But I have not tried it yet. Accordingly you have to use PreferenceFragment instead of PreferenceActivity.

JJD
  • 50,076
  • 60
  • 203
  • 339
Tea
  • 256
  • 3
  • 4
  • The accepted answer won't work for V7. Using setVisible does work for V7 – m12lrpv Oct 22 '18 at 08:15
  • V7 also has `getParent()`, so you can actually remove the preference as described in [this answer](https://stackoverflow.com/a/52336537/905686). – user905686 Oct 15 '20 at 14:25
3

In the XML file you can make a hidden preference by leaving the title and summary tags empty.

<EditTextPreference
    android:defaultValue="toddlerCam"
    android:key="save_photo_dir"
/>
Neuron
  • 5,141
  • 5
  • 38
  • 59
Al Ro
  • 466
  • 2
  • 11
3

Since Android API 26 getParent() method is available: https://developer.android.com/reference/android/preference/Preference.html#getParent()

Though you can do the following:

preference.getParent().removePreference(preference);
amukhachov
  • 5,822
  • 1
  • 41
  • 60
2

Here's a generic way to do this that works regardless of whether the preference is under a PreferenceCategory or PreferenceScreen.

private void removePreference(Preference preference) {
    PreferenceGroup parent = getParent(getPreferenceScreen(), preference);
    if (parent == null)
        throw new RuntimeException("Couldn't find preference");

    parent.removePreference(preference);
}

private PreferenceGroup getParent(PreferenceGroup groupToSearchIn, Preference preference) {
    for (int i = 0; i < groupToSearchIn.getPreferenceCount(); ++i) {
        Preference child = groupToSearchIn.getPreference(i);

        if (child == preference)
            return groupToSearchIn;

        if (child instanceof PreferenceGroup) {
            PreferenceGroup childGroup = (PreferenceGroup)child;
            PreferenceGroup result = getParent(childGroup, preference);
            if (result != null)
                return result;
        }
    }

    return null;
}
Sam
  • 40,644
  • 36
  • 176
  • 219
2

There is a simple workaround:

//In your Activity code after finding the preference to hide:
    if(pref!=null) {
        pref.setEnabled(false);
        pref.setSelectable(false);
        //Following line will replace the layout of your preference by an empty one
        pref.setLayoutResource(R.layout.preference_hidden);
    }

And create a preference_hidden layout:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="0dp"/>

Wherever is your Preference to hide (in a PreferenceGroup or at root) it will work!

TwiXter
  • 181
  • 2
  • 9
  • Thank you. Worked for me perfectly. But for make sure I added: `android:visibility="gone"` – Mic Apr 06 '23 at 07:47
0

If you want to evaluate, and based on that mask, an alternative may be

SwitchPreference autenticacionUsuario = 
    (SwitchPreference) findPreference("key_autenticacion_usuario");

final EditTextPreference Username = 
    (EditTextPreference) findPreference("key_username_mqtt");
final EditTextPreference Password = 
    (EditTextPreference) findPreference("key_password_mqtt");

if (!autenticacionUsuario.isChecked()) {
    PreferenceCategory preferenceCategory = 
        (PreferenceCategory) findPreference("category_mqtt");
    preferenceCategory.removePreference(Username);
    preferenceCategory.removePreference(Password);
}

All this must be within

public static class PrefsFragment extends PreferenceFragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
Community
  • 1
  • 1
0

You can do this in 2 ways:

1.If you use support library, you can build a map of the tree of preferences and their parents, and then remove a preference by using its parent. Here's a function to generate such a map:

public static Map<Preference, PreferenceGroup> buildPreferenceParentTree(@NonNull final PreferenceScreen preferenceScreen) {
    final Map<Preference, PreferenceGroup> result = new HashMap<>();
    final Stack<PreferenceGroup> curParents = new Stack<>();
    curParents.add(preferenceScreen);
    while (!curParents.isEmpty()) {
        final PreferenceGroup parent = curParents.pop();
        final int childCount = parent.getPreferenceCount();
        for (int i = 0; i < childCount; ++i) {
            final Preference child = parent.getPreference(i);
            result.put(child, parent);
            if (child instanceof PreferenceGroup)
                curParents.push((PreferenceGroup) child);
        }
    }
    return result;
}
  1. If you use the new android-x preference API, you can just set the visibility, by using setVisible function on it.
android developer
  • 114,585
  • 152
  • 739
  • 1,270
  • According to the [docs](https://developer.android.google.cn/reference/android/support/v7/preference/Preference#setVisible(boolean)) and [Tea's answer](https://stackoverflow.com/a/44448823/356895) `setVisible()` is available since version 24.1.0 of the Support library. – JJD Jan 11 '19 at 07:46
  • Have you looked at what I wrote? I specifically wrote that it's possible now... Also, the first solution helps with removal, which is a bit different than hiding.. – android developer Jan 11 '19 at 09:33
  • Yes, I read your answer. I was referring to your 2nd point. It reads to as if the `setVisibile()` method is available from _android-x_ which I tried to clarify. No offense please. – JJD Jan 11 '19 at 09:38
  • Android-X is the one to replace all support libraries. There won't be any new versions of support library as we know them. – android developer Jan 11 '19 at 09:50
  • Correct. I am [aware of this](https://developer.android.com/topic/libraries/support-library/revisions). Still, people who are stucked with former versions can make use of the method. – JJD Jan 11 '19 at 10:20
0

If you're doing what I think you're trying to do (because I'm trying to do it now) it might be better to enable/disable the preference. Because removing it takes it out of the preference screen and you might not be able to add it back where you want it if you made the screen programmatically.

pref.setEnabled(false); pref.setEnabled(true);

although this might be deprecated. It works for the use case that I'm going through right now.

RCB
  • 560
  • 4
  • 9
0

If all you need is not to show the preference i.e. hide the preference then do the following

findPreference<Preference>("keyName").isVisible = false

code is in kotlin

Note : This is AndroidX preferences (don't know if same with hold with earlier Preference)

Saksham Khurana
  • 872
  • 13
  • 26
0

Instead of doing this in onCreate in the settings activity:

getSupportFragmentManager().beginTransaction().replace(R.id.settings_container, new SettingsFragment()).commit();

You can initialize a global variable for the settings fragment and set it up like this:

settingsFragment = new SettingsFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.settings_container, settingsFragment).commit();

Then you can do something like this further down in onCreate to set what should be hidden based on existing preferences, or to change what is hidden/visible based on conditions in your OnSharedPreferenceChangeListener:

settingsFragment.findPreference("setting key").setVisible(false);
ATL
  • 444
  • 6
  • 10