Thursday, February 9, 2012

Modifying Preferences in a Preference Activity

So you've got yourself a preference screen, and for whatever reason you need to programatically remove one of the prefs.  In our case, this is generally because we have some kind of variant build of our product -- like a version that doesn't support 'custom images' for example.

Inevitably, first you try something like this, and it doesn't work:

PreferenceScreen prefs = getPreferenceScreen();
Preference p = prefs.findPreference( "pref_to_remove" );
prefs.removePreference(p);

Sometimes, this will work, but often it doesn't!  What's up with that?  Well, most of our preference screens are divided up into categories, mostly because it looks nicer this way.  As it turns out, if you do that the individual prefs aren't actually owned by the PreferenceScreen, they're owned by the category they're in instead.  This means you need to do something more like this:

PreferenceScreen prefs = getPreferenceScreen();
Preference p = prefs.findPreference( "pref_to_remove" );
PreferenceCategory cat = (PreferenceCategory) prefs.findPreference( "category_name" );
cat.removePreference(p);

At which point, it will actually work.  The PreferenceCategory is the actual owner of the pref.

Hopefully this will save somebody some confusion in the future.

No comments:

Post a Comment