PreferenceCategory.removePreference()返回false,因此不删除首选项

时间:2015-08-05 13:47:15

标签: android android-preferences preferenceactivity preferencefragment

我已经在SO上看到了与此问题相关的所有问题,但没有一个对我有用。我正在尝试删除从PreferenceFragment类中的xml文件加载的首选项,但删除该首选项。

这是我的 pref_screen.xml 文件

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

    <PreferenceCategory>

    <! ------------ />

    <Preferencecategory>

    <PreferenceCategory
         android:key="device_section">

        <Preference 
            android:key="sound"
            android:icon="@drawable/ic_settings_icon"
            android:title="@string/sound">
        </Preference>

        <Preference
            android:key="storage_settings"
            android:title="@string/storage_settings"
            android:icon="@drawable/ic_settings_storage">
        <Preference>

    </PreferenceCategory>

    <PreferenceCategory>

    <! ------------------ />

    </PreferenceCategory>

</PreferenceScreen>

这是我的 PreferenceFragment 类:

public static class PrefFragment extends PreferenceFragment {

    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.pref_screen);

        final Preference storage = getPreferenceScreen().findPreference("storage_settings");

        if(storage != null){
            Log.d("SettingsActivity : ", "findPreference(storage_settings) not returning null.");
        }

        final PreferenceCategory device_prefCat = 
            (PreferenceCategory) getPreferenceScreen().findPreference("device_section");

        if(device_prefCat != null){
            Log.d("SettingsActivity : " , "findPreference(device_section) not returning null.");
        }


        if(device_prefCat.removePreference(storage)){
            Log.d("SettingsActivity : ", "device_prefCat() returns true.");
        }else{
            Log.d("SettingsActivity : ", "device_prefCat() returns false");
        }
    }

我查了一下日志。 findPreference()未返回null,但removePreference()正在返回false。请告诉我我做错了什么。

1 个答案:

答案 0 :(得分:0)

根据我在this thread中发现的信息,以下内容应该对您有用:

Preference storage = findPreference("storage_settings");
PreferenceCategory device_prefCat = (PreferenceCategory) findPreference("device_section");
device_prefCat.removePreference(storage)

请注意,我不是在这里故意使用getPreferenceScreen()