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"/>
相关推荐
雨白6 小时前
Java 线程通信基础:interrupt、wait 和 notifyAll 详解
android·java
诺诺Okami10 小时前
Android Framework-Launcher-UI和组件
android
潘潘潘11 小时前
Android线程间通信机制Handler介绍
android
潘潘潘11 小时前
Android动态链接库So的加载
android
潘潘潘12 小时前
Android多线程机制简介
android
CYRUS_STUDIO13 小时前
利用 Linux 信号机制(SIGTRAP)实现 Android 下的反调试
android·安全·逆向
CYRUS_STUDIO14 小时前
Android 反调试攻防实战:多重检测手段解析与内核级绕过方案
android·操作系统·逆向
黄林晴18 小时前
如何判断手机是否是纯血鸿蒙系统
android
火柴就是我18 小时前
flutter 之真手势冲突处理
android·flutter
法的空间18 小时前
Flutter JsonToDart 支持 JsonSchema
android·flutter·ios