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().removePreference(p);
// worked == false.
So the preference is found, but the removePreference() call fails. What's the right way to do this? I'm using a preference.xml file for the keys like so:
<PreferenceScreen
xmlns:android="http://schemas.a开发者_运维知识库ndroid.com/apk/res/android">
<PreferenceCategory
android:title="foo">
<CheckBoxPreference
android:key="grok" />
...
Thanks
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:
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:key="category_foo"
android:title="foo">
<CheckBoxPreference
android:key="grok" />
...
Code:
Preference p = findPreference("grok");
// removing Preference
((PreferenceGroup) findPreference("category_foo")).removePreference(p);
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:
public static Map<Preference,PreferenceGroup> buildPreferenceParentTree(final PreferenceActivity activity)
{
final Map<Preference,PreferenceGroup> result=new HashMap<Preference,PreferenceGroup>();
final Stack<PreferenceGroup> curParents=new Stack<PreferenceGroup>();
curParents.add(activity.getPreferenceScreen());
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;
}
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.
精彩评论