一、效果图
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详解:链接。