How To Remove A Preference From Preferenceactivity?
I'm using PreferenceActivity. How do I remove a preference? I cannot seem to get this to work: Preference p = findPreference('grok'); boolean worked = getPreferenceScreen().removeP
Solution 1:
you can remove only exact child in PreferenceGroup. So in your case, you should add some key to PreferenceCategory (with title="foo"), then findPreference with this key & then remove it child
XML:
<PreferenceScreenxmlns:android="http://schemas.android.com/apk/res/android"><PreferenceCategoryandroid:key="category_foo"android:title="foo"><CheckBoxPreferenceandroid:key="grok" />
...
Code:
Preferencep= findPreference("grok");
// removing Preference
((PreferenceGroup) findPreference("category_foo")).removePreference(p);
Solution 2:
Instead of setting multiple ids, you can get the entire tree of preferences and find the parent of any preference, and then remove any of its children preferences:
publicstatic Map<Preference,PreferenceGroup> buildPreferenceParentTree(final PreferenceActivity activity)
{
final Map<Preference,PreferenceGroup> result=newHashMap<Preference,PreferenceGroup>();
final Stack<PreferenceGroup> curParents=newStack<PreferenceGroup>();
curParents.add(activity.getPreferenceScreen());
while(!curParents.isEmpty())
{
final PreferenceGroup parent=curParents.pop();
finalint 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;
}
example:
final Map<Preference,PreferenceGroup> preferenceParentTree=buildPreferenceParentTree(SettingsActivity.this);
final PreferenceGroup preferenceParent=preferenceParentTree.get(preferenceToRemove);
preferenceGroup.removePreference(preferenceToRemove);
EDIT: seems there is a new API for this :
https://developer.android.com/reference/androidx/preference/Preference#setVisible(boolean)
I'm not sure if currently it's available or not, though.
Post a Comment for "How To Remove A Preference From Preferenceactivity?"