关于Switch控件的使用

本文介绍如何通过设置Android Switch控件的属性来自定义其外观样式,包括调整宽度、显示文本及设置背景图片等。

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

使用Switch控件是,默认样式一搬不能满足我们的需求,但是通过一些属性的使用,我们就能得到我们想要的样式。

<Switch
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:switchMinWidth="35dp"
    android:showText="true"
    android:textOn=""
    android:textOff=""
    android:thumb="@drawable/switch_thumb"
    android:track="@drawable/switch_track"/>
其中:

switchMinWidth:表示开关最小宽度

showText 表示是否显示textOn和textOff的内容

textOn表示开关打开时的文案

textOff表示开关关闭时的文案

thumb表示开关滑块的图片,可以是selector

track表示开关背景图片,可以是selector

switch_track为:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/blue_track" android:state_checked="true"/>
    <item android:drawable="@drawable/grey_track"/>
</selector>

blue_track:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <size android:height="20dp"/>
    <corners android:radius="10dp"/>
    <gradient
        android:endColor="@color/main_blue"
        android:startColor="@color/main_blue"/>
</shape>
grey_track:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <size android:height="20dp"/>
    <corners android:radius="10dp"/>
    <gradient
        android:endColor="@color/main_disable"
        android:startColor="@color/main_disable"/>
</shape>


switch_thumb为:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/switch_thumb_checked" android:state_checked="true"/>
    <item android:drawable="@drawable/switch_thumb_reset"/>
</selector>
switch_thumb_checked:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="oval"
       android:useLevel="false">
    <solid android:color="@color/main_white"/>
    <stroke
        android:width="1dp"
        android:color="@color/main_blue"/>
    <size
        android:width="20dp"
        android:height="20dp"/>
</shape>
switch_thumb_reset:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="oval"
       android:useLevel="false">
    <solid android:color="@color/main_white"/>
    <stroke
        android:width="1dp"
        android:color="@color/main_line"/>
    <size
        android:width="20dp"
        android:height="20dp"/>

</shape>

如果要修改开关的高度,直接修改track中的height属性即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值