直接上代码
1. 定义按钮开的状态 switch_on
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#F64245" />
<size android:width="@dimen/dp_18" android:height="@dimen/dp_18" />
</shape>
2.定义按钮关的状态 switch_off
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#A2A2A2" />
<size android:width="@dimen/dp_18" android:height="@dimen/dp_18" />
</shape>
3.创建按钮状态选择器
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/switch_on" android:state_checked="true" />
<item android:drawable="@drawable/switch_off" android:state_checked="false" />
</selector>
4.定义开关开启状态的背景色switch_bg_on
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#ffffff" />
<size android:width="@dimen/dp_42" android:height="@dimen/dp_18" />
<stroke android:width="@dimen/dp_1" android:color="#F64245" />
<corners android:radius="@dimen/dp_13" />
</shape>
5.定义开关关闭状态的背景色switch_bg_off
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#ffffff" />
<size android:width="@dimen/dp_42" android:height="@dimen/dp_18" />
<stroke android:width="@dimen/dp_1" android:color="#CFCFCF" />
<corners android:radius="@dimen/dp_13" />
</shape>
6.创建按钮背景状态选择器
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/switch_bg_on" android:state_checked="true" />
<item android:drawable="@drawable/switch_bg_off" android:state_checked="false" />
</selector>
7.应用和其他设置
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:switchMinWidth="@dimen/dp_46"
android:showText="false"
android:thumb="@drawable/switch_selector"
android:track="@drawable/switch_bg_selector" />
文字的显示与隐藏 android:showText="false"
调证控件大小 wigth 和 height 不起作用,所以用android:switchMinWidth
网友评论