问题
I have a preference xml ..
first im loading the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
and setting some default values to it... After setting the default values , i need to hide (not to remove) one of my preference screen
My preference XML is
<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>
I need to hide the PreferenceScreen
having
title ="@string/account_2
回答1:
easy as:
Preference preference = (Preference) findPreference("pref");
PreferenceScreen preferenceScreen = (PreferenceScreen) findPreference("pref_screen");
PreferenceCategory preferenceCategory = (PreferenceCategory) findPreference("pref_category");
To hide the Preference:
PreferenceGroup preferenceParent = getParent(preference);
preferenceParent.removePreference(preference);
To hide the PreferenceScreen:
PreferenceGroup preferenceScreenParent = getParent(preferenceScreen);
preferenceScreenParent.removePreference(preferenceScreen);
To hide the PreferenceCategory:
PreferenceGroup preferenceCategoryParent = getParent(preferenceCategory);
preferenceCategoryParent.removePreference(preferenceCategory);
And the same manner goes to EditTextPreference, CheckBoxPreference, .....
回答2:
You can duplicate your XML. Then remove the second part like this:
<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>
Then you check your preference to see if it has already been initialized.
If yes, you load the XML above, otherwise the first one.
回答3:
If you have a reference to both the Preference, and its parent (a PreferenceCategory, or PreferenceScreen)
myPreferenceScreen.remove(myPreference);
来源:https://stackoverflow.com/questions/7282817/hide-a-preference-screen-in-android