自定义switch

博客介绍了在布局中添加控件及相关XML文件的步骤,包括在布局中加入控件,以及添加selector_thumb.xml、switch_red_thumb.xml等多个XML文件。

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

1.第一步在布局中加入下面控件

  <Switch
       android:id="@+id/switch_hide"
       android:layout_width="wrap_content"
       android:layout_height="31dp"
       android:layout_alignParentRight="true"
       android:layout_centerVertical="true"
       android:textOff=""
       android:textOn=""
       android:thumb="@drawable/selector_thumb"
       android:track="@drawable/selector_track" />

2.添加selector_thumb.xml文件

<?xml version="1.0" encoding="utf-8"?>
<!-- 按钮的选择器,可以设置按钮在不同状态下的时候,按钮不同的颜色 -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/switch_red_thumb" android:state_checked="true" />
    <item android:drawable="@drawable/switch_gray_thumb" />
</selector>

3.添加switch_red_thumb.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <size
        android:width="30dp"
        android:height="30dp" />
    <corners android:radius="15dp" />
    <solid android:color="@color/color_ffffff"/>
    <stroke
        android:width="1dp"
        android:color="@color/color_cc3433" />
</shape>

4.添加switch_gray_thumb.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <size
        android:width="30dp"
        android:height="30dp" />
    <corners android:radius="15dp" />
    <solid android:color="@color/color_ffffff"/>
    <stroke
        android:width="1dp"
        android:color="@color/color_line" />
</shape>

5添加selector_track.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- 底层下滑条的样式选择器,可控制Switch在不同状态下,底下下滑条的颜色 -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/switch_red_track" android:state_checked="true" />
    <item android:drawable="@drawable/switch_gray_track" />
</selector>

6.添加switch_red_track.xml

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

7.添加switch_gray_track.xml

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值