Android 自定义Switch,仿微信开关键Switch

本文详细介绍如何在Android中自定义开关控件的外观和状态,包括创建滑动圆点、选中和非选中样式,以及如何在布局文件中应用这些自定义样式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

switch (changeFragmentEvent.getViewId()) {

    //启动设备(安卓接收)
    case 1:
        textView.setText("vvvvv555"+changeFragmentEvent.getstring());

        break;
    case 2:
        textView.setText("vvvvv555WWW22");
        break;
}

 

效果

实现方法

1、drawable下创建滑动圆点  switch_thumb

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="oval">
    <size
        android:width="30dp"
        android:height="30dp">
    </size>
    <solid
        android:color="@android:color/white">
    </solid>

</shape>

switch_thumb增加透明边框

<stroke
    android:width="9pt"
    android:color="@color/transparent" />

 

2、drawable下创建选中样式   switch_track_on

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">

    <solid
        android:color="@color/businesstop">
    </solid>

    <corners
        android:radius="30dp">
    </corners>

</shape>

3、drawable下创建非选中样式    switch_track_off

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <solid
        android:color="@android:color/darker_gray">
    </solid>
    <corners
        android:radius="30dp">
    </corners>
</shape>

 

4、drawable下创建switch样式   switch_track

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:state_checked="true"
        android:drawable="@drawable/switch_track_on"></item>
    <item
        android:state_checked="false"
        android:drawable="@drawable/switch_track_off"></item>
</selector>

5、layout.xml下switch引用自定义滑动点和样式即可

<Switch
    android:id="@+id/ycsw"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:thumb="@drawable/switch_thumb"
    android:track="@drawable/switch_track"
    android:gravity="center"/>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值