Android UI之switch的thumb与track属性定制自己的switch

本文介绍如何通过定义Thumb和Track的图片来自定义Switch的样式。详细步骤包括创建滑动块的Drawable文件、设置不同状态下的Track颜色,并在布局文件中应用这些自定义样式。

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

转自:http://blog.youkuaiyun.com/u012585142/article/details/50756872
今天发现需要使用控件switch,但是需要自定义switch的样式,通过查阅资料,发现可以通过定义switch的thumb和track的图片来达到自定义switch样式的目的.现把相关的步骤记录下来,以备查阅。
这里写图片描述
其中1为所需样式,2为系统自定义样式
1、创建thumb(即来回滑动的滑动块)利用XML来定义一个drawable文件,命名为switch_thumb

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size
    android:width="25dp"
    android:height="25dp">
</size>
<!-- 填充的颜色:这里设置滑动块为白色 -->
<solid android:color="@color/white" />
<!--<solid android:color="@color/theme_color" />-->
****<!-- 边框的颜色 :因为需要显示一点点背景色,所以设置了一个透明边框 -->**
<stroke
    android:width="2dp"
    android:color="@android:color/transparent" />**
<!--<corners android:radius="2dip" />-->
<corners android:radius="2dip" />
</shape>

2、track属性又该如何设置呢?
问题在于打开switch与关闭switch,switch的下面的滑道应该是不同的颜色,我们想到了可以用drawable的selector标签,利用switch的不同状态,来加载不同的drawable文件。我们查看官方switch文档,发现其有
void setChecked(boolean checked) Changes the checked state of this button.
这样一个方法,所以我们可以利用其state_checked状态,依据不同的状态来选择加载不同的drawable文件
1):首先,我们定义一个drawable文件:switch_track_on.xml

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

<corners android:radius="2dip" />
</shape>

2):再定义一个drawable文件:switch_track_off.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!--<size-->
    <!--android:width="60dp"-->
    <!--android:height="35dp">-->
<!--</size>-->
<solid
    android:color="@android:color/darker_gray">
</solid>
<corners android:radius="2dip" />
</shape>

3):然后定义drawable文件:switch_track.xml

<?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>

最后在布局文件

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值