Android switch控件的使用,及简单样式改变

本文介绍了如何在Android项目中实现开关效果,针对API 5.0及以上和以下的不同,提供两种不同的实现方式。在API 21及以上版本,使用默认风格;在API 21以下版本,通过在`switch_item.xml`布局文件中设置背景图片来实现开关切换效果。
摘要由CSDN通过智能技术生成

最近因为项目需要,要求5.0要有开关的效果,5.0以下开关就是图片的改变。


做法:

1、新建21文件夹:

2、在layout和layout-v21文件夹内分别新建一个文件:switch_item.xml

3、21文件夹内的xml填充内容,使用默认的风格:

<Switch xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android中自定义Switch控件可以通过自定义drawable来实现。以下是一个简单的例子: 1. 创建一个drawable资源文件,例如 switch_bg.xml,用于定义Switch的背景样式: ```xml <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="true" android:drawable="@drawable/switch_on_bg" /> <item android:state_checked="false" android:drawable="@drawable/switch_off_bg" /> </selector> ``` 2. 创建两个drawable资源文件,例如 switch_on_bg.xml 和 switch_off_bg.xml,分别用于定义Switch开和关状态下的样式switch_on_bg.xml: ```xml <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#00FF00" /> <corners android:radius="20dp" /> </shape> ``` switch_off_bg.xml: ```xml <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#FF0000" /> <corners android:radius="20dp" /> </shape> ``` 3. 在布局文件中使用自定义Switch控件: ```xml <Switch android:id="@+id/customSwitch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:thumb="@drawable/custom_switch_thumb" android:track="@drawable/switch_bg" /> ``` 其中,android:thumb属性定义了Switch的拇指(即开关按钮)的样式。我们可以创建一个自定义drawable来实现: ```xml <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <solid android:color="#FFFFFF" /> <size android:width="20dp" android:height="20dp" /> </shape> ``` 这样就完成了自定义Switch控件样式。当Switch状态改变时,背景样式也会随之改变。你可以根据自己的需求来修改样式
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值