用 Android 基础 Switch 控件实现自定义样式,
先上效果:
image.png实现代码:
布局中写法:
<Switch
android:id="@+id/switchBtn"
android:layout_width="wrap_content"
android:layout_height="@dimen/dp_26"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_marginEnd="@dimen/dp_15"
android:thumb="@drawable/switch_thumb"
android:track="@drawable/switch_track_selector" />
相关配置文件
- switch_thumb.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="@color/c_ff71a5" />
<!-- stroke 用来控制中间实心按钮的外边距 -->
<stroke
android:width="@dimen/dp_6"
android:color="#00000000" />
<!-- size 设置整体大小 -->
<size
android:width="@dimen/dp_26"
android:height="@dimen/dp_26" />
</shape>
- switch_track_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/switch_track_on" android:state_checked="true" />
<item android:drawable="@drawable/switch_track_off" android:state_checked="false" />
</selector>
- 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="@color/c_ff71a5_20" />
<corners android:radius="@dimen/dp_15" />
</shape>
- 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="@color/color_f4" />
<corners android:radius="@dimen/dp_15" />
</shape>
网友评论