在android中隐藏首选项屏幕

我有一个偏好xml ..

首先从XML资源加载首选项

 addPreferencesFromResource(R.xml.preferences); 

并为其设置一些默认值…设置默认值后,我需要隐藏(不删除)我的首选项屏幕

我的偏好XML是

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

    <Preference
                android:title="Account Settings"
                 android:key="customPref" />

    <PreferenceScreen android:title="@string/account_1"
                    android:key="account">
            <EditTextPreference
                android:key="username"
                android:title="@string/settings_username"
                android:singleLine="true" />
            <EditTextPreference
                android:key="password"
                android:title="@string/settings_password"
                android:password="true"
                android:singleLine="true" />
                </PreferenceScreen>


    <PreferenceScreen android:title="@string/account_2"
                android:key="account1">
            <EditTextPreference
                android:key="username1"
                android:title="@string/settings_username"
                android:singleLine="true" />
            <EditTextPreference
                android:key="password1"
                android:title="@string/settings_password"
                android:password="true"
                android:singleLine="true" />
                </PreferenceScreen>
</PreferenceScreen>

我需要隐藏PreferenceScreen

title ="@string/account_2

解决方法:

容易:

Preference preference = (Preference) findPreference("pref");
PreferenceScreen preferenceScreen = (PreferenceScreen) findPreference("pref_screen");
PreferenceCategory preferenceCategory = (PreferenceCategory) findPreference("pref_category");

要隐藏首选项:

PreferenceGroup preferenceParent = getParent(preference);
preferenceParent.removePreference(preference);

隐藏PreferenceScreen:

PreferenceGroup preferenceScreenParent = getParent(preferenceScreen);
preferenceScreenParent.removePreference(preferenceScreen);

隐藏PreferenceCategory:

PreferenceGroup preferenceCategoryParent = getParent(preferenceCategory);
preferenceCategoryParent.removePreference(preferenceCategory);

同样的方式去EditTextPreference,CheckBoxPreference,…..

上一篇:如何在Android中获取对象的首选项类型?


下一篇:Flutter 数据存储之 shared_preferences