前言
讲解基本Switch的使用与记录一些开发点子
转载请注明来源:https://www.cnblogs.com/guanxinjing/p/16313742.html
基本属性
- android:showText:设置on/off的时候是否显示文字,boolean
- android:splitTrack:是否设置一个间隙,让滑块与底部图片分隔,boolean
- android:switchMinWidth:设置开关的最小宽度
- android:switchPadding:设置滑块内文字的间隔
- android:switchTextAppearance:设置开关的文字外观,暂时没发现有什么用...
- android:textOff:按钮没有被选中时显示的文字
- android:textOn:按钮被选中时显示的文字
- android:textStyle:文字风格,粗体,斜体写划线那些
- android:track:底部的图片
- android:thumb:滑块的图片
设置状态监听
mBinding.timeFormatSwitch.setOnCheckedChangeListener { switchView, isChecked -> if (switchView.isPressed){ } }
自定义Switch
效果图
背景xml
要做到滑块thumb大于背景的关键是android:top 与 android:bottom(注意是item里的属性)这里的属性类似于 android:layout_marginTop
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="true"> <layer-list> <item android:top="3dp" android:bottom="3dp"> <shape android:shape="rectangle"> <corners android:radius="10dp"/> <gradient android:type="linear" android:angle="0" android:startColor="#48F3D0" android:endColor="#1DBBFF"/> </shape> </item> </layer-list> </item> <item android:state_checked="false"> <layer-list> <item android:top="3dp" android:bottom="3dp"> <shape android:shape="rectangle"> <corners android:radius="10dp"/> <solid android:color="#646464"/> </shape> </item> </layer-list> </item> </selector>
滑块xml
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <size android:width="30dp" android:height="30dp"/> <solid android:color="#ffffff"/> </shape>
在view里设置它们
<androidx.appcompat.widget.SwitchCompat android:id="@+id/timeFormatSwitch" android:layout_width="60dp" android:layout_height="30dp" android:layout_marginEnd="35dp" app:track="@drawable/settings_selector_shape_rectangle_48f3d0_10dp" android:thumb="@drawable/settings_shape_oval_ffffff_30dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" />
End
本文来自博客园,作者:观心静 ,转载请注明原文链接:https://www.cnblogs.com/guanxinjing/p/16313742.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!