实现效果
实现方案
- 背景: switch_track.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/switch_selected_track" android:state_checked="true" />
<item android:drawable="@drawable/switch_unselected_track" />
</selector>
- 滑块: switch_thumb.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<!-- 滑动块的宽高 -->
<size
android:width="20dp"
android:height="20dp" />
<solid android:color="#FFFFFF" />
<!-- 透明的描边-->
<stroke
android:width="3dp"
android:color="@android:color/transparent" />
</shape>
- 选中背景:switch_selected_track.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size android:height="20dp" />
<corners android:radius="10dp" />
<solid android:color="#00C653" />
</shape>
- 未选中背景: switch_unselected_track.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<size android:height="20dp"/>
<corners android:radius="10dp"/>
<solid android:color="#D9D9D9" />
</shape>
- 使用方法
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:switchMinWidth="20dp"
android:thumb="@drawable/switch_thumb"
android:track="@drawable/switch_track" />
基础样例完整源代码
https://gitee.com/hspbc/SwitchDemo