直接上代碼
1. 定義按鈕開的狀態(tài)??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.定義按鈕關(guān)的狀態(tài) 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.創(chuàng)建按鈕狀態(tài)選擇器
<?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.定義開關(guān)開啟狀態(tài)的背景色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.定義開關(guān)關(guān)閉狀態(tài)的背景色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.創(chuàng)建按鈕背景狀態(tài)選擇器
<?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.應(yīng)用和其他設(shè)置
<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"
調(diào)證控件大小 wigth 和 height 不起作用,所以用android:switchMinWidth?