android 快速实现 Switch 样式

需要自定义6个文件

1.滑块开启: switch_thumb_on.xml

XML 复制代码
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#3171D1" />
    <size
        android:width="30dp"
        android:height="30dp" />
</shape>

2.滑块关闭: switch_thumb_off.xml

XML 复制代码
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#CACACA" />
    <size
        android:width="30dp"
        android:height="30dp" />
</shape>

3.滑块selector:switch_thumb_selector.xml

XML 复制代码
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/switch_thumb_on" android:state_checked="true" />
    <item android:drawable="@drawable/switch_thumb_off" android:state_checked="false" />
</selector>

4.滑块管道开启:switch_track_on.xml

XML 复制代码
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#94D2EE" />
    <!-- 设置stroke透明可以让滑块管道变小点 -->
    <stroke
        android:width="5dp"
        android:color="@android:color/transparent" />
    <!-- 设置corners 圆角15dp对应滑块的size=30dp的一半(显示为半圆) -->
    <corners android:radius="15dp" />
</shape>

5.滑块管道关闭:switch_track_off.xml

XML 复制代码
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#F5F0F0" />
    <!-- 设置stroke透明可以让滑块管道变小点 -->
    <stroke
        android:width="5dp"
        android:color="@android:color/transparent" />
    <!-- 设置corners 圆角15dp对应滑块的size=30dp的一半(显示为半圆) -->
    <corners android:radius="15dp" />
</shape>

6.滑块管道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>

7.布局使用:

XML 复制代码
 <Switch
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:track="@drawable/switch_track_selector"
     android:thumb="@drawable/switch_thumb_selector"/>
相关推荐
Just_Paranoid3 小时前
【Settings】恢复出厂设置密码校验
android·python·settings·sha256·hmac-sha256
肥肥呀呀呀5 小时前
flutter配置Android gradle kts 8.0 的打包名称
android·flutter
平生不喜凡桃李8 小时前
C++ 异常
android·java·c++
Propeller9 小时前
【Android】View 交互的事件处理机制
android·java
吴Wu涛涛涛涛涛Tao9 小时前
Flutter 实现「可拖拽评论面板 + 回复输入框 + @高亮」的完整方案
android·flutter·ios
雨声不在9 小时前
使用android studio分析cpu开销
android·ide·android studio
程序leo源10 小时前
Linux_基础指令(二)
android·linux·运维·服务器·青少年编程
雨白13 小时前
Android 两种拖拽 API 详解:ViewDragHelper 和 OnDragListener 的原理与区别
android
元亓亓亓13 小时前
JavaWeb--day3--Ajax&Element&路由&打包部署
android·ajax·okhttp