一、效果图
1、默认


2、自定义


二、上代码
1、创建thumb
shape_switch_thumb_true.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<!--设置大小-->
<size android:width="20dp"
android:height="20dp"/>
<!--设置圆角-->
<corners android:radius="10dp"/>
<!--设置背景颜色-->
<solid android:color="@color/white"/>
<!--设置边框-->
<stroke android:width="2dp" android:color="@color/red"/>
</shape>
shape_switch_thumb_false.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<!--设置大小-->
<size android:width="20dp"
android:height="20dp"/>
<!--设置圆角-->
<corners android:radius="10dp"/>
<!--设置背景颜色-->
<solid android:color="@color/white"/>
<!--设置边框-->
<stroke android:width="2dp" android:color="@color/silver"/>
</shape>
selector_switch_thumb.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!--选中状态ture-->
<item android:drawable="@drawable/shape_switch_thumb_true" android:state_checked="true"/>
<!--选中状态false-->
<item android:drawable="@drawable/shape_switch_thumb_false" android:state_checked="false"/>
</selector>
2、创建track
shape_switch_track_true.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<!--设置大小-->
<size android:width="40dp"
android:height="20dp"/>
<!--设置圆角-->
<corners android:radius="10dp"/>
<!--设置背景颜色-->
<solid android:color="@color/red"/>
</shape>
shape_switch_track_false.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<!--设置大小-->
<size android:width="40dp"
android:height="20dp"/>
<!--设置圆角-->
<corners android:radius="10dp"/>
<!--设置背景颜色-->
<solid android:color="@color/silver"/>
</shape>
selector_switch_track.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!--选中状态ture-->
<item android:drawable="@drawable/shape_switch_track_true" android:state_checked="true"/>
<!--选中状态false-->
<item android:drawable="@drawable/shape_switch_track_false" android:state_checked="false"/>
</selector>
3、设置Swicth属性
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:thumb="@drawable/selector_switch_thumb"
android:track="@drawable/selector_switch_track"
tools:ignore="UseSwitchCompatOrMaterialXml" />
三、链接
1、Switch官方API:链接。
2、shape详解:链接。
本文详细介绍了如何自定义Android Switch的thumb和track,通过创建XML形状资源文件,设置不同状态的颜色和边框,然后在Switch组件中应用这些选择器,实现开关切换时的视觉效果变化。同时提供了完整的代码示例,帮助开发者理解并实现自定义开关样式。
1345

被折叠的 条评论
为什么被折叠?



