Android资源知识(六)之控件状态State List

State List资源是定义在XML中,用来指定控件在不同状态时更换不同的背景图片,从而提高用户体验。例如,Button控件的以下几种状态:pressed, focused, neither。我们可以用State List为Button的每一种状态提供不同的背景图片。
文件路径:res/drawable/filename.xml
引用方式:
In Java: R.drawable.filename
In XML: @[package:]drawable/filename
语法示例:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:constantSize=["true" | "false"]
    android:dither=["true" | "false"]
    android:variablePadding=["true" | "false"] >
    <item
        android:drawable="@[package:]drawable/drawable_resource"
        android:state_pressed=["true" | "false"]
        android:state_focused=["true" | "false"]
        android:state_hovered=["true" | "false"]
        android:state_selected=["true" | "false"]
        android:state_checkable=["true" | "false"]
        android:state_checked=["true" | "false"]
        android:state_enabled=["true" | "false"]
        android:state_activated=["true" | "false"]
        android:state_window_focused=["true" | "false"] />
</selector>

代码示例:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
          android:drawable="@drawable/button_pressed" /> <!-- pressed -->
    <item android:state_focused="true"
          android:drawable="@drawable/button_focused" /> <!-- focused -->
    <item android:state_hovered="true"
          android:drawable="@drawable/button_focused" /> <!-- hovered -->
    <item android:drawable="@drawable/button_normal" /> <!-- default 此项一定要放在最后面-->
</selector>
<Button
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:background="@drawable/button" />

注意:default item的顺序问题!!!

Remember that Android applies the first item in the state list that matches the current state of the object. So, if the first item in the list contains none of the state attributes above, then it is applied every time, which is why your default value should always be last (as demonstrated in the following example).

官方温馨提示:State List中第一个item匹配的是当前现行状态,因此,如果第1个item项包含了无状态属性,那么控件的每一种状态变化都将作用于这个属性。通俗的讲,也就是你的默认值必须总是放在最后一项,就像上面示例当中的那样default的那一项放在State List的最后面。否则,你的控件状态将不会改变,一定要注意item的顺序问题,切记!!



文/kinbos(简书作者)
原文链接:http://www.jianshu.com/p/0044a18cf0be
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值