android自定义drawable的state属性
在drawable中使用selector在开发中太常用了,不过用的最多是根据系统提供的一些状态来选择图片,比如:android:state_checked
、android: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