使用Switch控件是,默认样式一搬不能满足我们的需求,但是通过一些属性的使用,我们就能得到我们想要的样式。
<Switch android:layout_width="wrap_content" android:layout_height="wrap_content" android:switchMinWidth="35dp" android:showText="true" android:textOn="" android:textOff="" android:thumb="@drawable/switch_thumb" android:track="@drawable/switch_track"/>其中:
switchMinWidth:表示开关最小宽度
showText 表示是否显示textOn和textOff的内容
textOn表示开关打开时的文案
textOff表示开关关闭时的文案
thumb表示开关滑块的图片,可以是selector
track表示开关背景图片,可以是selector
switch_track为:
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/blue_track" android:state_checked="true"/> <item android:drawable="@drawable/grey_track"/> </selector>
blue_track:
<shape xmlns:android="http://schemas.android.com/apk/res/android"> <size android:height="20dp"/> <corners android:radius="10dp"/> <gradient android:endColor="@color/main_blue" android:startColor="@color/main_blue"/> </shape>grey_track:
<shape xmlns:android="http://schemas.android.com/apk/res/android"> <size android:height="20dp"/> <corners android:radius="10dp"/> <gradient android:endColor="@color/main_disable" android:startColor="@color/main_disable"/> </shape>
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/switch_thumb_checked" android:state_checked="true"/> <item android:drawable="@drawable/switch_thumb_reset"/> </selector>switch_thumb_checked:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" android:useLevel="false"> <solid android:color="@color/main_white"/> <stroke android:width="1dp" android:color="@color/main_blue"/> <size android:width="20dp" android:height="20dp"/> </shape>switch_thumb_reset:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" android:useLevel="false"> <solid android:color="@color/main_white"/> <stroke android:width="1dp" android:color="@color/main_line"/> <size android:width="20dp" android:height="20dp"/> </shape>
如果要修改开关的高度,直接修改track中的height属性即可。