android自定义drawable的state属性

android自定义drawable的state属性

在drawable中使用selector在开发中太常用了,不过用的最多是根据系统提供的一些状态来选择图片,比如:android:state_checkedandroid:state_pressed等等,其实这些状态也是可以自定义的,比方说天气状况有很多种情况,天晴、多云、下雨等等,那能不能根据这些状况来显示不同的示意图呢?这里是指通过 selector的方式来实现。答案是肯定的,下面的效果图就是用selector来实现的。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-R1Zgi0aC-1584662459361)(https://raw.githubusercontent.com/MingHuang1024/illustrations/master/drawable_state.gif)]

上面动画中的天气图标、背景、文字颜色都是用selector来实现的,没有在代码中根据不同天气设置图片等,不过文字是在代码中改变的。

下面来看下怎么实现:

一、定义表示状态的属性

在res-values目录中新建一个attrs.xml文件(已有则不必新建),定义以下三个属性,代表天气中的天晴、多云、下雨

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="Weather">
    <attr name="state_sunny" format="boolean"/>
    <attr name="state_raining" format="boolean"/>
    <attr name="state_cloudy" format="boolean"/>
    </declare-styleable>
</resources>

二、使用selector定义drawable

在res-drawable中新建一个weather_icon.xml文件,根据天气状态来显示相应的图片

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" 	
		  xmlns:example="http://schemas.android.com/apk/res-auto">

    <item android:drawable="@drawable/sunny" example:state_sunny="true" />

    <item android:drawable="@drawable/raining" example:state_raining="true" />

    <item android:drawable="@drawable/cloudy" example:state_cloud
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值