这里只需要定义三个属性即可实现自定义的效果:
1.switchMinWidth属性,需要定义最小宽度,否则会变形
2.thumb属性,设置自定义的开关图片,这里我用的白色圆形
3.track属性,这个很重要,只有这个属性才能使开关的切换事件得到自己想要的效果
android:textOff=""
android:textOn=""
这两个属性是去掉开关上的文字
代码如下
<Switch
android:id="@+id/switchUsername"android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:switchMinWidth="44dp"
android:textOff=""
android:textOn=""
android:thumb="@drawable/white_btn"
android:track="@drawable/switch_track" />
switch_track.xml文件
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/off_btn" android:state_enabled="false"/>
<item android:drawable="@drawable/on_btn" android:state_pressed="true"/>
<item android:drawable="@drawable/on_btn" android:state_checked="true"/>
<item android:drawable="@drawable/off_btn"/>
</selector>
至于上面的时间属性大家自己去看,这里不做过多介绍。