原生的SwitchCompat控件如下图,不说不堪入目,也算是不敢恭维了。开个玩笑...
所以我们就需要对SwitchCompat进行自定义风格,效果如下图
代码如下
<androidx.appcompat.widget.SwitchCompat
android:id="@+id/switch_compat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:thumb="@drawable/switch_thumb"
app:switchMinWidth="60dp"
app:track="@drawable/switch_track_style" />
从上面的xml代码来看其实只需要定制两个东西一个是thumb,另一个是track
switch_thumb
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="@color/white" />
<size
android:width="50dp"
android:height="50dp" />
<!-- 这里的5dp边距的作用是,圆点在轨道里面的边距,这样的效果感觉更好 -->
<stroke
android:width="5dp"
android:color="#00000000" />
<corners android:radius="15dp" />
</shape>
switch_track_style
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/switch_common_track_selected" android:state_checked="true" />
<item android:drawable="@drawable/switch_common_track_unselected" android:state_checked="false" />
</selector>
switch_track_style里面有两个背景如下
switch_common_track_selected
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item >
<shape android:shape="rectangle">
<solid android:color="#23c3ff" />
<size android:height="30dp" />
<stroke
android:color="#00000000" />
<corners android:radius="30dp" />
</shape>
</item>
</layer-list>
switch_common_track_unselected
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#4D8E8E8E" />
<size android:height="30dp" />
<stroke
android:color="#00000000" />
<corners android:radius="30dp" />
</shape>
</item>
</layer-list>
完活了!!!