前言
由于最近需要實(shí)現(xiàn)一個(gè)自定義的switch奕翔,本想寫(xiě)一個(gè)MySwitch繼承Switch來(lái)進(jìn)行自定義降盹,但是后來(lái)發(fā)現(xiàn)其實(shí)只需要通過(guò)定義switch的thumb和track的圖片來(lái)達(dá)到自定義switch樣式的目的护戳。
實(shí)現(xiàn)
1.定義track
track即滑動(dòng)的軌道金闽。
在res/drawable內(nèi)先定義一個(gè)軌道關(guān)閉狀態(tài)的drawable隧饼,switch_gray_track.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<!-- switch的高度-->
<size android:height="20dp"/>
<corners android:radius="10dp"/>
<solid android:color="#D9D9D9" />
</shape>
再定義一個(gè)軌道開(kāi)啟狀態(tài)的drawable乖菱,switch_yellow_track.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size android:height="20dp" />
<corners android:radius="10dp" />
<solid android:color="#FECD15" />
</shape>
最后定義一個(gè)selector作為軌道的樣式乖寒,switch_track.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/switch_yellow_track" android:state_checked="true" />
<item android:drawable="@drawable/switch_gray_track" />
</selector>
2.定義thumb
thumb即滑動(dòng)塊蒙秒。
在res/drawable內(nèi)定義一個(gè)滑動(dòng)塊的drawable,switch_thumb.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<!-- 滑動(dòng)塊的寬高 -->
<size
android:width="20dp"
android:height="20dp" />
<solid android:color="#FFFFFF" />
<!-- 透明的描邊-->
<stroke android:width="3dp"
android:color="@android:color/transparent"/>
</shape>
增加了一個(gè)透明的描邊宵统,不然白色的小滑塊就完全覆蓋掉了外面的軌道晕讲。
3.設(shè)置Switch
修改android:layout_width,android:layout_height 這兩個(gè)屬性马澈,并不會(huì)實(shí)際修改Switch的大小設(shè)置大了瓢省,邊上會(huì)出現(xiàn)空白部分,設(shè)置小了痊班,Switch顯示不全勤婚。
Switch的高度是由track的高度決定的,寬度呢則可以通過(guò)設(shè)置switchMinWidth(開(kāi)關(guān)最小寬度 )來(lái)更改涤伐。
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:switchMinWidth="20dp"
android:track="@drawable/switch_track"
android:thumb="@drawable/switch_thumb"/>
源碼
github: https://github.com/JeremySun823/MySwitchTest