效果:
可以通过定义switch的thumb(滑块)和track(轨道)的图片来达到自定义switch样式的目的,现把相关的步骤记录下来,然后用选择器selector来实现switch的不同状态,来加载不同的drawable文件。
1.创建switch_custom_thumb_on.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size
android:width="20dp"
android:height="20dp" />
<solid android:color="@color/white" />
<!-- 边框的颜色 :因为需要显示一点点背景色,所以设置了一个透明边框 -->
<stroke
android:width="5dp"
android:color="@android:color/transparent" />
<corners android:radius="2dip" />
</shape>
2.创建switch_custom_thumb_off.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size
android:width="20dp"
android:height="20dp" />
<solid android:color="#FF3D3D3D" />
<!-- 边框的颜色 :因为需要显示一点点背景色,所以设置了一个透明边框 -->
<stroke
android:width="5dp"
android:color="@android:color/transparent" />
<corners android:radius="2dip" />
</shape>
3.创建switch_custom_track_on.xml ,注意track(轨道)的大小会受到thumb(滑块)的影响,就是说可以调整thumb的大小,然后track的大小也会跟着自动改变,因此可以只调整thumb大小来确定track大小,所有这里的大小被注释。
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!-- <size
android:width="150dp"
android:height="20dp">
</size>-->
<solid android:color="#4175C4"/>
<corners android:radius="2dip" />
</shape>
4.创建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">
<!-- <size
android:width="150dp"
android:height="20dp">
</size>-->
<solid android:color="#CACACA" />
<corners android:radius="2dip" />
</shape>
5.创建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>
6.创建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_thumb_on" android:state_checked="true" />
<item android:drawable="@drawable/switch_custom_thumb_off" android:state_checked="false" />
</selector>
7.switch使用前面定义的样式
<Switch
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:thumb="@drawable/switch_custom_thumb_selector"
android:track="@drawable/switch_custom_track_selector" />
完成