自定义Switch样式
自定义Switch首先要熟悉两个属性,thumb与trace
-. thumb 代表按钮的意思,就是switch左右两边那个
-. trace 代表轨迹的意思,就是thumb在来回滑动过程中变化的轨迹
. 自定义thumb
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#fff"/>
<size android:width="30dp"
android:height="30dp"/>
<corners android:radius="180dp"/>
</shape>
上述代码就是创建了一个宽高相同的thumb,当然如果你有其他需求也可以改成其他大小颜色的
自定义trace关闭状态
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#dbdbdb"/>
<corners android:radius="20dp"/>
</shape>
自定义trace打开状态
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#fe8a01"/>
<corners android:radius="20dp"/>
</shape>
自定义trace选择器
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/shape_switch_track_open" android:state_checked="true"/>
<item android:drawable="@drawable/shape_switch_track_close"
android:state_checked="false"/>
<item android:drawable="@drawable/shape_switch_track_close"
/>
</selector>
最终的应用
<Switch
android:id="@+id/st_switch"
android:layout_width="wrap_content"
app:layout_constraintTop_toBottomOf="@id/toolbar"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:thumb="@drawable/shape_switch_thumb"
android:track="@drawable/shape_switch_track_selector"
android:layout_height="wrap_content" />
最后
switch的大小是跟thumb的大小有关