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"/>
相关推荐
teacher伟大光荣且正确4 小时前
Qt Creator 配置 Android 编译环境
android·开发语言·qt
飞猿_SIR7 小时前
Android Exoplayer 实现多个音视频文件混合播放以及音轨切换
android·音视频
HumoChen997 小时前
GZip+Base64压缩字符串在ios上解压报错问题解决(安卓、PC模拟器正常)
android·小程序·uniapp·base64·gzip
沙振宇11 小时前
【HarmonyOS】ArkTS开发应用的横竖屏切换
android·华为·harmonyos
橙子1991101613 小时前
Kotlin 中的作用域函数
android·开发语言·kotlin
zimoyin13 小时前
Kotlin 懒初始化值
android·开发语言·kotlin
枣伊吕波14 小时前
第六节第二部分:抽象类的应用-模板方法设计模式
android·java·设计模式
萧然CS14 小时前
使用ADB命令操作Android的apk/aab包
android·adb
_extraordinary_18 小时前
MySQL 事务(二)
android·数据库·mysql
鸿蒙布道师1 天前
鸿蒙NEXT开发动画案例5
android·ios·华为·harmonyos·鸿蒙系统·arkui·huawei