有些人對Switch控件的 android:thumb和 android:track兩個屬性理解不清楚和明白,現在跟大家講清楚這兩個屬性的作用。
Switch主要有兩個屬性構成:上面圓形的滑塊,下面的滑道。
android:thumb對應的滑塊
android:track 對應的滑道。
1、先來看Switch默認樣式,如下:
checked=false,滑塊和滑道都是灰色。
checked=true,滑塊是深粉紅色,滑道是淺粉紅色
對應的xml:
<Switch android:checked="true" android:layout_width="wrap_content" android:layout_height="wrap_content"></Switch>
2、設置滑道樣式,如圖:
checked=false,滑塊還是系統默認顏色白色,滑道變成深灰色。
checked=true,滑塊還是系統默認顏色深粉紅色,滑道變成淺綠色。
樣式和xml代碼:
在資源的drawable目錄下創建switch_track_off.xml 文件,如下:
switch_track_off.xml 文件:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="@android:color/darker_gray"> </solid> <corners android:radius="30dp"> </corners> </shape>
switch_track_on.xml 文件
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="@android:color/holo_green_light"> </solid> <corners android:radius="32dp"> </corners> </shape>
switch_track.xml 文件
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="true" android:drawable="@drawable/switch_track_on"></item> <item android:state_checked="false" android:drawable="@drawable/switch_track_off"></item> </selector>
布局文件:
<Switch android:checked="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:track="@drawable/switch_track"></Switch>
3、設置滑塊樣式:
在第二步上,設置滑塊樣式,checked=false,滑塊由系統默認的白色改為黑色,滑道還是第二步的灰色。
checked=true,滑塊由系統默認的深粉紅色改為藍色,滑道還是第二步的綠色。
在資源的drawable目錄下創建switch_thumb_off.xml 文件,如下:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <size android:width="30dp" android:height="30dp"> </size> <solid android:color="#000000"> </solid> </shape>
switch_thumb_on.xml :
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <size android:width="30dp" android:height="30dp"> </size> <solid android:color="#0000ff"> </solid> </shape>
switch_thumb.xml :
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="true" android:drawable="@drawable/switch_thumb_on"></item> <item android:state_checked="false" android:drawable="@drawable/switch_thumb_off"></item> </selector>
布局文件:
<Switch android:checked="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:track="@drawable/switch_track" android:thumb="@drawable/switch_thumb"></Switch>
上面已經把Switch 的android:thumb和 android:track屬性講清楚了。