1.1 原生样式
首先看下原生的效果 (Android 7.1):
原生效果
布局文件如下:
- <Switch
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
1.2 自定义样式
设计给的效果图大多数都不会使用原生效果, 所以我们需要对样式进行自定义, 比如下面这种效果:
自定义效果
定义 Switch 的开关按钮状态:
开启状态: switch_custom_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="#94C5FF" />
- <size
- android:width="20dp"
- android:height="20dp" />
- </shape>
关闭状态: switch_custom_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="#AAA" />
- <size
- android:width="20dp"
- android:height="20dp" />
- </shape>
定义一个 selector:switch_custom_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_custom_thumb_on" android:state_checked="true" />
- <item android:drawable="@drawable/switch_custom_thumb_off" android:state_checked="false" />
- </selector>
到此 Switch 的开关按钮状态就定义好了, 接下来定义一下 Switch 滑动轨道的状态:
开启状态: switch_custom_track_on.xml
- <?xml version="1.0" encoding="utf-8" ?>
- <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
- <solid android:color="#B6D6FE" />
- <stroke android:width="5dp" android:color="#00000000" />
- <corners android:radius="20dp" />
- </shape>
关闭状态: switch_custom_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="#E3E3E3" />
- <stroke android:width="5dp" android:color="#00000000" />
- <corners android:radius="20dp" />
- </shape>
定义一个 selector:switch_custom_track_selector.xml
- <?xml version="1.0" encoding="utf-8"?>
- <selector xmlns:android="http://schemas.android.com/apk/res/android">
- <item android:drawable="@drawable/switch_custom_track_on" android:state_checked="true" />
- <item android:drawable="@drawable/switch_custom_track_off" android:state_checked="false" />
- </selector>
Switch 自定义样式, 默认情况下开关按钮和滑动轨道的高度是一样的, 并且在 xml 文件中对轨道的宽高设置是无效的, 如果想要修改轨道的高度可以这样做:
轨道高度低于开关按钮高度 (效果中的第一个效果): 轨道增加一个透明的边框
轨道高度高于开关按钮高度 (效果中的第二个效果): 开关按钮增加一个透明的边框
轨道的宽度会随着开关按钮的宽度自动变化, 如果想要修改轨道的宽度, 修改开关按钮的宽度就可以了
设置自定义样式
thumb 是开关按钮的属性, track 是滑动轨道的属性, 只需要把上面的两个 selector 文件设置进去就大功告成了
- <Switch
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:thumb="@drawable/switch_custom_thumb_selector"
- android:track="@drawable/switch_custom_track_selector" />
来源: https://mp.weixin.qq.com/s?__biz=MzIwMzYwMTk1NA==&mid=2247489710&idx=1&sn=6037872bd8147782b2d04e5c4125b0e0