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"/>
相关推荐
GEEKVIP18 分钟前
手机使用技巧:8 个 Android 锁屏移除工具 [解锁 Android]
android·macos·ios·智能手机·电脑·手机·iphone
model20052 小时前
android + tflite 分类APP开发-2
android·分类·tflite
彭于晏6892 小时前
Android广播
android·java·开发语言
与衫3 小时前
掌握嵌套子查询:复杂 SQL 中 * 列的准确表列关系
android·javascript·sql
500了10 小时前
Kotlin基本知识
android·开发语言·kotlin
人工智能的苟富贵10 小时前
Android Debug Bridge(ADB)完全指南
android·adb
小雨cc5566ru15 小时前
uniapp+Android面向网络学习的时间管理工具软件 微信小程序
android·微信小程序·uni-app
bianshaopeng16 小时前
android 原生加载pdf
android·pdf
hhzz17 小时前
Linux Shell编程快速入门以及案例(Linux一键批量启动、停止、重启Jar包Shell脚本)
android·linux·jar
火红的小辣椒18 小时前
XSS基础
android·web安全