IT圈内那点事儿Android技术知识程序员

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

2016-11-08  本文已影响89人  码道成功

    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的顺序问题,切记!!

上一篇 下一篇

猜你喜欢

热点阅读