Android Settings中Preference的理解以及使用

article/2025/11/6 5:06:19

      Preference 是Android App 中重要的控件之一,Settings 模块大部分都是通过 Preference 实现

优点:

        Preference 可以自动显示我们上次设置的数据,Android提供preference这个键值对的方式来处理这种情况,自动保存这些数据,并立时生效,无需用户自己保存操作,只需要在xml中定义对应的Preference控件即可。

PreferenceActivity和PreferenceFragment:

        PreferenceActivity是一个非常有用的基类,当我们开发Android项目时避免不了选项设置,这些设置习惯用Preference来保存。Android专门为这种Activity提供了便捷的基PreferenceActivity。如果继承自Preference则不需要自己控制Preference的读写,PreferenceActivity会为我们处理一切。

        PreferenceActivity与普通的Activity不同,它不是使用界面布局文件,而是使用选项设置的布局文件。选项设置布局文件以PreferenceScreen作为根元素来表示定义一个参数设置界面布局。

       从Android 3.0以后官方不再推荐直接让PreferenceActivity加载选项设置布局文件,而是建议使用PreferenceFragment,PreferenceFragment  源码布局实际就是一个RecyclerView,通过读取Preference的布局来作为其item,通过adapter适配器展示

Preference的介绍和使用

 1.preference常用控件
             Preference 控件家庭          View控件家庭         控件含义                   

               Preference                         TextView                文本框                      

              CheckPreference                CheckBox              单选框                  

              EditTextPreference              EditText               输入文本框            

              ListPreference                     ListView                  列表框             

              RingtonePreference          ——                            铃声

              PreferenceCategory        类似于LinearLayou、RelativeLayout,用于组合一组Preference,使布局更具备层次感 。

              PreferenceScreen            所有Preference元素的根节点
 2.使用 需要加入依赖

 implementation ("androidx.preference:preference:1.2.0-alpha01")

(1)在res文件下定义xml文件夹,定义 test.xml;如下

(2)xml文件中是定义的preference控件

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:settings="http://schemas.android.com/tools"><PreferenceCategoryandroid:key="test2"android:title="第二组设置"><CheckBoxPreferenceandroid:defaultValue="false"android:key="g2_checkbox_key"android:summaryOff="关"android:summaryOn="开"android:title="第二组设置勾选" /><ListPreferenceandroid:dialogIcon="@android:drawable/stat_sys_warning"android:dialogTitle="第二组列表设置"android:key="g2_list_key"android:summary="选择"android:title="第一组列表设置" /></PreferenceCategory><SwitchPreferenceandroid:defaultValue="false"android:key="show_advanced_setting"android:summary="高级设置"android:title="显示高级设置" /><PreferenceCategory android:key="yh"><com.android.test3.prefence.RestrictedSwitchPreferenceandroid:defaultValue="true"android:icon="@drawable/ic_settings_wireless"android:key="login_dji_account"android:title="蓝牙" /><com.android.test3.prefence.RestrictedSwitchPreferenceandroid:defaultValue="true"android:icon="@drawable/ic_launcher_background"android:key="login_dji_account1"app:allowDividerAbove="true"android:title="网络" /><com.android.test3.prefence.RestrictedPreferenceandroid:icon="@drawable/ic_launcher_background"android:key="internet_settings"android:order="20"android:summary=" SAA"android:title="互联网"app:allowDividerAbove="true"settings:keywords="@string/keywords_internet"settings:useAdminDisabledSummary="true" /><com.android.test3.prefence.LuxPreferenceandroid:icon="@drawable/ic_settings_wireless"android:summary="ww"app:allowDividerAbove="true"android:title="测试自动" /><com.android.test3.prefence.LuxArrowPreferenceandroid:icon="@drawable/ic_settings_wireless"android:summary="ww"android:title="开始" /></PreferenceCategory></PreferenceScreen>

 (3)新建类PrefFragment.java,让其继承PreferenceFragment,并加载选项设置的布局文件:(核心代码是第6行和13行)

package com.android.test3.fragment;
import android.os.Bundle;import androidx.annotation.Nullable;
import androidx.preference.PreferenceFragmentCompat;import com.android.test3.R;/*** @author hudebo* @desc* @date 2022/11/11*/
public class PowerFragment extends PreferenceFragmentCompat {@Overridepublic void onCreatePreferences(@Nullable Bundle savedInstanceState, @Nullable String rootKey) {//从xml文件加载选项 setPreferencesFromResource(R.xml.pref_two, rootKey);}
}

(4)然后,在MainActivity.java中加载上面的Fragment:

package com.android.test3;import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.android.test3.fragment.PowerFragment;public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);getSupportFragmentManager().beginTransaction().replace(R.id.content,new PowerFragment() ).commitAllowingStateLoss();}}

自定义Preference

有时候原生的preference满足不了我们的需求,比如,加个背景,加个其他控件等;此时就需要我们自定义控件解决

 比如:(1)给布局设置背景;我们继承Preference;在onBindViewHolder 方法中对通过holder获取控件其进行设置

package com.android.test3.prefence;import android.content.Context;
import android.util.AttributeSet;import androidx.core.content.res.TypedArrayUtils;
import androidx.preference.Preference;
import androidx.preference.PreferenceViewHolder;import com.android.test3.PrefenceFeatureManager;
import com.android.test3.R;/*** @author hudebo* @desc 自定义子Preference 支持圆角; 去除summary  支持icon title* @date 2022/11/24*/
public class LuxPreference extends Preference {public LuxPreference(Context context, AttributeSet attrs, int defStyleAttr) {this(context, attrs, defStyleAttr, 0);}public LuxPreference(Context context, AttributeSet attrs) {this(context, attrs, TypedArrayUtils.getAttr(context, R.attr.luxPreferenceStyle,android.R.attr.preferenceStyle));}public LuxPreference(Context context) {this(context, null);}public LuxPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {super(context, attrs, defStyleAttr, defStyleRes);}@Overridepublic void onBindViewHolder(PreferenceViewHolder holder) {super.onBindViewHolder(holder);if (holder != null) {PrefenceFeatureManager.setPrefenceBackground(this, holder.itemView);}}
}

(2)修改布局控件;a.首先我们在layout中定义绘制你的布局样式

 b.在自定义控件中引入你的布局即可

声明:setLayoutResource 方法即是覆盖原始preference的主布局;setWidgetLayoutResource 方法是覆盖原始布局的WidgetLayout的控件;如下图是preference的源码布局;

 setLayoutResource 是替换除了"@android:id/widget_frame" 这个控件的部分;setWidgetLayoutResource只是替换"@android:id/widget_frame"部分;如果setWidgetLayoutResource不设置也不影响;说明你得,右边没有布局

<?xml version="1.0" encoding="utf-8"?>
<!--~ Copyright (C) 2015 The Android Open Source Project~~ Licensed under the Apache License, Version 2.0 (the "License");~ you may not use this file except in compliance with the License.~ You may obtain a copy of the License at~~      http://www.apache.org/licenses/LICENSE-2.0~~ Unless required by applicable law or agreed to in writing, software~ distributed under the License is distributed on an "AS IS" BASIS,~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.~ See the License for the specific language governing permissions and~ limitations under the License.--><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="wrap_content"android:minHeight="?android:attr/listPreferredItemHeightSmall"android:gravity="center_vertical"android:paddingLeft="?android:attr/listPreferredItemPaddingLeft"android:paddingStart="?android:attr/listPreferredItemPaddingStart"android:paddingRight="?android:attr/listPreferredItemPaddingRight"android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"android:background="?android:attr/selectableItemBackground"android:clipToPadding="false"android:baselineAligned="false"><include layout="@layout/image_frame"/><RelativeLayoutandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:paddingTop="16dp"android:paddingBottom="16dp"><TextViewandroid:id="@android:id/title"android:layout_width="wrap_content"android:layout_height="wrap_content"android:singleLine="true"android:textAppearance="?android:attr/textAppearanceListItem"android:ellipsize="marquee"/><TextViewandroid:id="@android:id/summary"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@android:id/title"android:layout_alignLeft="@android:id/title"android:layout_alignStart="@android:id/title"android:layout_gravity="start"android:textAlignment="viewStart"android:textColor="?android:attr/textColorSecondary"android:maxLines="10"style="@style/PreferenceSummaryTextStyle"/></RelativeLayout><!-- Preference should place its actual preference widget here. --><LinearLayoutandroid:id="@android:id/widget_frame"android:layout_width="wrap_content"android:layout_height="match_parent"android:gravity="end|center_vertical"android:paddingLeft="16dp"android:paddingStart="16dp"android:paddingRight="0dp"android:paddingEnd="0dp"android:orientation="vertical"/></LinearLayout>

以上就是一些个人理解;像通用的preference属性;以及点击等相关方法后续介绍; 喜欢的点个赞吧!!!


http://chatgpt.dhexx.cn/article/2jnTunft.shtml

相关文章

使用 Android PreferenceScreen 偏好显示类(android.preference.PreferenceScreen)

http://edu.gamfe.com/tutor/d/36925.html PreferenceScreen preference是偏好&#xff0c;首选的意思&#xff0c;PreferenceScreen个人翻译成 “偏好显示”&#xff0c;明白这个意思就好&#xff0c;就是说根据特点灵活的定义显示内容风格&#xff0c;一个屏幕可以包含多个风…

android开发之PreferenceScreen使用详解

一 PreferenceActivity 1、PreferenceActivity概述 PreferenceActivity是一个抽象类&#xff0c;继承于ListActivity&#xff0c;以列表形式视图来展现界面,加载的整个View也是基于ListActivity中那个ListView的&#xff0c;其最主要的优势在于添加Preference后可让其状态持久化…

Android PreferenceScreen的使用和详解(设置页面)

PreferenceScreen是设置选项的配置文件&#xff0c;一般用在设置页面&#xff0c;用来当前的状态是保存在。该状态无须用户处理&#xff0c;存在SharedPreferences中。 1.如何使用 1.1布局文件的创建 PreferenceScreen的用法和layout的类似&#xff0c;都是通过xml文件来管理…

Semaphore - 信号量的简单介绍与使用

一、Semaphore使用 // Test_Semaphore.cpp : 定义控制台应用程序的入口点。 //#include "stdafx.h" #include <windows.h> #include <iostream> #include <time.h>using namespace std;const int g_num 3; HANDLE g_semp[g_num] { NULL }; HAND…

C++中多线程管理

1&#xff0c;函数1 CreateSemaphore 创建或打开一个信号量&#xff0c;信号可以理解为停车场&#xff0c;创建和增加信号&#xff0c;可以理解为创建一个停车场&#xff0c;和可以停放的汽车&#xff0c; 如下&#xff1a; CreateSemaphore(NULL, 2, 3, szSemaphoreA);//开…

lspci是如何工作的

目录 前言lspci那么系统是怎么知道每个PCIe设备具体是哪个厂商的哪种设备的&#xff1f; 前言 出于好奇&#xff0c;看了看lspci的工作原理&#xff0c;操作系统是怎么认识这么多PCIe设备的&#xff1b; lspci lspci用于查看当前系统所连接的所有PCI/PCIe设备&#xff1b; …

linux系统下怎么使用lspci,Linux系统之lspci命令介绍

lspci 顾名思义 就是显示所有的pci设备信息。pci是一种总线 而通过pci总线连接的设备就是pci设备了。如今 我们常用的设备很多都是采用pci总线了 如 网卡、存储等。下面就简单介绍下该命令。 lspci 显示所有的pci设备信息。包括设备的BDF 设备类型 厂商信息等。 lspci -t [BDF]…

lspci 和 setpci 的几种用法

1、指定pci 地址查看 2、查看vender id 3、查看 pcie 地址空间数据 4、修改 pci 地址空间的数据 setpci 读地址0xd0的值 setpci -v -s 01:00.0 d0.w 写地址0xd0的值 setpci -v -s 01:00.0 d0.w0x0101

lspci 详解 pci 拓扑结构 与 pci 树形结构

一、PCIE 拓扑结构 硬盘是大家都很熟悉的设备&#xff0c;一路走来&#xff0c;从HDD到SSD&#xff0c;从SATA到NVMe&#xff0c;作为NVMe SSD的前端接口&#xff0c;PCIe再次进入我们的视野。作为x86体系关键的一环&#xff0c;PCIe标准历经PCI&#xff0c;PCI-X和PCIe&#…

lspci命令

一 lspci命令详解 lspci命令&#xff1a;列出整个系统的PCIe总线和设备 使用方式有如下几种&#xff1a; 列出整个系统的PCIe总线和设备 列出指定PCIe设备的ID信息&#xff0c;即vendor ID和device ID 具体命令如下所示&#xff1a; 从上述信息可知&#xff0c;该设备的vend…

lspci

1) 以树的形式打印pci设备 # lspci -t -v 2) -n 显示vendor 和 device id &#xff0c; -m 向后兼容显示pci 设备的数据 # lspci -v -m -n -s 00:04.0 3&#xff09;通过hexdump 查看pci设备的配置空间 # hexdump /sys/devices/pci0000\:00/0000\:00\:05.0/config 4&#xf…

lspci命令整理

1. 作用&#xff1a; 显示当前主机的所有PCI总线信息 2. 常用指令&#xff1a; lspci -nn 第一列的数字&#xff1a; 总线编号(Bus Number)&#xff1a;设备编号&#xff08;Device Number&#xff09;&#xff1a;功能编号&#xff08;Function Number&#xff09; 第一个中…

request.getSession.setAttribute和request.setAttribute区别

【方法1】request.getSession.setAttribute 【方法2】request.setAttribute 相信很多初学的小伙伴对方法1和方法2&#xff0c;也充满了疑问&#xff0c;因为他们俩的作用都是把参数存入内存中&#xff0c;然后取出&#xff0c;或者被其他方法调用&#xff0c;但是不知道什么情…

setAttribute()和setProperty()

setAttribute()和setProperty() 学习笔记 初学习完setAttribute()和setProperty()后&#xff0c;在项目中使用时不太清楚原理&#xff0c;总是一知半解&#xff0c;最近又遇到关于这两个属性的笔试题&#xff0c;决定更加深入的去理解这两个属性。 setAttribue()&#xff1a;…

request.getParameter()、request.setAttribute()与request.getAttribute()的作用

1、request.getParameter()方法是获取通过类似post&#xff0c;get等方式传入的数据&#xff0c;即获取客户端到服务端的数据&#xff0c;代表HTTP请求数据。 2、request.setAttribute()方法是将request.getParameter()方法获取的数据保存到request域中&#xff0c;即将获取的…

HttpURLConnection.setRequestProperty的作用

设置http请求头 HttpURLConnection.setRequestProperty&#xff08;String key&#xff0c;String value&#xff09;; 这个我居然都忘记了&#xff0c;哎~真是岁数大了&#xff0c;心好累。。。 例如&#xff1a;下面就是一个完整的原始网络请求方式 HttpURLConnection …

一个破解压缩包密码的软件——ziperello

最近安了一个软件&#xff0c;解压还要密码&#xff0c;先是关注公众号啥的&#xff0c;分享链接啥的&#xff0c;然后顺着网友的吐槽找到这款软件。 读取准备文件会花费几个小时&#xff0c;但是最后破解几秒就好啦 下载链接 链接&#xff1a;https://pan.baidu.com/s/17TxQVX…

关于破解邮箱的一点心得

最近开始想更换一个好点的邮箱域名&#xff0c;因为本人名字可能比较火&#xff0c;163 126 foxmail主流邮箱的所有简写和拼写id都被占用&#xff0c;想购买又无路可走&#xff0c;所以把注意打到破解邮箱上&#xff0c;做了很多尝试。 首先在网上百度了很多破解邮箱的工具&…

压缩包密码破解工具

压缩包在解压文件的时候需要输入密码才能解压成功&#xff0c;遇到这种情况&#xff0c;需要一款压缩包破解工具将密码找到&#xff0c;才能继续解压文件 破解工具&#xff1a;okfone 压缩包解密大师 链接 支持rar、zip、7z格式的压缩文件解密 方法&#xff1a; 将文件添加…

压缩文件解压密码破解之fcrackzip

写在前面&#xff1a;网上对fcrackzip相关知识很多&#xff0c;我就不多哔哔了&#xff0c;我比较喜欢直接掏出重点少废话&#xff0c;写的花留呼哨一坨官方术语各种夸、没必要大家都挺忙的。 工具简介&#xff1a;fcrackzip是一款专门破解zip类型压缩文件密码的工具&#xff…