简介
官方简介:
The Preference library allows you to build interactive settings screens, without needing to handle interacting with device storage or managing the user interface.
渣渣翻译:首选项库允许您构建交互式设置屏幕,而无需处理与设备存储的交互或管理用户界面。
代表着一种基本的 Preference 的UI控件,展示方式类似于 ListView 。
在我开发的过程没有遇到过,这次在 Settings 遇到,我们简单的学习一下。
XML 属性
android:key:key:唯一标识,SharedPreferences也将通过此Key值进行数据保存,也可以通过key值获取保存的信息。
android:defaultValue :默认值,例如,CheckPreference的默认值可为”true”,默认为选中状态。
android:enabled :表示该Preference是否可用状态。
android:title :每个Preference在PreferenceScreen布局上显示的标题——大标题。
android:summary :每个Preference在PreferenceScreen布局上显示的标题——小标题(可以没有)。
android:persistent:表示Preference元素所对应的值是否写入sharedPreferen文件中,如果是true,则表示写入;否则,则表示不写入该Preference元素的值。
android:layout:在一个preferenceactivity的偏好布局 用于填充view。
android:dependency:表示一个Preference(用A表示)的可用状态依赖另外一个Preference(用B表示)。B可用,则A可用;B不可用,则A不可用。
android:icon: 偏好图标,对于偏好选择图标必须是一个引用到另一个资源的形式或以packagetypename 主题属性。
android:disableDependentsState:与android:dependency相反。B可用,则A不可用;B不可用,则A可用。
android:order:表示偏好顺序。
android:shouldDisableView:是否被禁用,这种偏好是必须是布尔值true或false。 这也可能是一个参考的形式或主题属性packagetypename资源,packagetypename形式包含一个值相当于全局属性资源符号shoulddisableview相关方法。
android:selectable:偏好是否是可选的。
android:widgetLayout:可以做小部部件部分的布局。
android:fragment: 使用时,可以碎片化PreferenceActivity。
Perference 显示方式
PreferenceFragmentCompat
/**
* Inflates the given XML resource and adds the preference hierarchy to the current
* preference hierarchy.
*
* @param preferencesResId The XML resource ID to inflate.
*/
public void addPreferencesFromResource(@XmlRes int preferencesResId) {
requirePreferenceManager();
setPreferenceScreen(mPreferenceManager.inflateFromResource(mStyledContext,
preferencesResId, getPreferenceScreen()));
}
/**
* Inflates the given XML resource and replaces the current preference hierarchy (if any) with
* the preference hierarchy rooted at {@code key}.
*
* @param preferencesResId The XML resource ID to inflate.
* @param key The preference key of the {@link androidx.preference.PreferenceScreen}
* to use as the root of the preference hierarchy, or null to use the root
* {@link androidx.preference.PreferenceScreen}.
*/
public void setPreferencesFromResource(@XmlRes int preferencesResId, @Nullable String key) {
requirePreferenceManager();
final PreferenceScreen xmlRoot = mPreferenceManager.inflateFromResource(mStyledContext,
preferencesResId, null);
final Preference root;
if (key != null) {
root = xmlRoot.findPreference(key);
if (!(root instanceof PreferenceScreen)) {
throw new IllegalArgumentException("Preference object with key " + key
+ " is not a PreferenceScreen");
}
} else {
root = xmlRoot;
}
setPreferenceScreen((PreferenceScreen) root);
}