Android 官方 switch 控件更改选中色

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
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状态改变时,背景样式也会随之改变。你可以根据自己的需求来修改样式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值