需要自定义6个文件
1.滑块开启: switch_thumb_on.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#3171D1" />
<size
android:width="30dp"
android:height="30dp" />
</shape>
2.滑块关闭: switch_thumb_off.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#CACACA" />
<size
android:width="30dp"
android:height="30dp" />
</shape>
3.滑块selector:switch_thumb_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/switch_thumb_on" android:state_checked="true" />
<item android:drawable="@drawable/switch_thumb_off" android:state_checked="false" />
</selector>
4.滑块管道开启:switch_track_on.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#94D2EE" />
<!-- 设置stroke透明可以让滑块管道变小点 -->
<stroke
android:width="5dp"
android:color="@android:color/transparent" />
<!-- 设置corners 圆角15dp对应滑块的size=30dp的一半(显示为半圆) -->
<corners android:radius="15dp" />
</shape>
5.滑块管道关闭:switch_track_off.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#F5F0F0" />
<!-- 设置stroke透明可以让滑块管道变小点 -->
<stroke
android:width="5dp"
android:color="@android:color/transparent" />
<!-- 设置corners 圆角15dp对应滑块的size=30dp的一半(显示为半圆) -->
<corners android:radius="15dp" />
</shape>
6.滑块管道selector:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/switch_track_on" android:state_checked="true" />
<item android:drawable="@drawable/switch_track_off" android:state_checked="false" />
</selector>
7.布局使用:
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:track="@drawable/switch_track_selector"
android:thumb="@drawable/switch_thumb_selector"/>