8.1.3 Android 中的 13 种 Drawable 小结 Part 3
收尾 Android 13 种 Drawable 的最后四类:LayerDrawable 层叠、TransitionDrawable 双层淡入淡出、LevelListDrawable 分级切换与 StateListDrawable 状态选择器。
学完这一章,你能够
- 收尾 Android 13 种 Drawable 的最后四类:LayerDrawable 层叠、TransitionDrawable 双层淡入淡出、LevelListDrawable 分级切换与 StateListDrawable 状态选择器。
LayerDrawable 与 TransitionDrawable
`LayerDrawable`(根节点 `<layer-list>`)管理一个有序的 Drawable 图层数组,绘制时按声明顺序从底向上叠加,索引最大的图层位于最上方。每个 `<item>` 可设置 `drawable`(或内嵌 Drawable 子节点)、`id` 以及相对容器的 `left`/`right`/`top`/`bottom` 偏移。典型实战包括两类:一是结合 `@android:id/background` 与带 `<clip>` 的 `@android:id/progress` 定制 `SeekBar` 进度轨道;二是为三层 `<bitmap>` 分别设置 `0dp`、`25dp`、`50dp` 的 `left`/`top` 偏移,零代码实现图片阶梯层叠效果。
`TransitionDrawable`(根节点 `<transition>`)是 `LayerDrawable` 的子类,专用于管理恰好两层 Drawable 之间的交叉淡入淡出动画(声明超过两层不会参与过渡)。在代码中获取 `TransitionDrawable` 后调用 `startTransition(durationMillis)` 可在指定时长内由第一层渐变为第二层,调用 `reverseTransition(durationMillis)` 则反向过渡;若需多图循环淡入淡出,可结合 `Handler` 定时替换两层图像并重启过渡。
LevelListDrawable 与 StateListDrawable
`LevelListDrawable`(根节点 `<level-list>`)将一组 Drawable 按 `android:minLevel` 与 `android:maxLevel` 区间映射起来,绘制时依据当前 level 选择首个满足区间的 `<item>`。例如将 5 个不同尺寸的圆形 `shape_cir1..5.xml` 分别映射到 `maxLevel` `2000`、`4000`、`6000`、`8000`、`10000`,在 `MainActivity` 中通过定时器循环调用 `img_show.setImageLevel()` 即可实现分档缩放或信号格指示效果。
`StateListDrawable`(根节点 `<selector>`)是按钮与交互控件最常用的状态选择器,可根据控件状态自动切换外观。常用状态属性包括 `state_focused`、`state_window_focused`、`state_enabled`、`state_checkable`、`state_checked`、`state_selected`、`state_pressed`、`state_active`、`state_single`、`state_first`、`state_middle` 与 `state_last`。需特别注意匹配规则:Android 严格**自上而下**寻找第一条完全匹配的 `<item>`,因此不带任何状态条件的默认正常状态项(如 `<item android:drawable="@drawable/shape_btn_normal"/>`)必须放在列表**最后**(正如 `selector_btn.xml` 所示),若误放在最前会拦截后续所有按压/选中状态。至此 13 类 Drawable 全部梳理完毕,示例源码包 `DrawableDemo.zip` 因源站停采限制未联网抓取并已登记。
验证 Layer/Transition/LevelList/StateList 四类 Drawable XML 解析与匹配规则
"""Offline verification lab for Android Ch 107: tutorial-drawable3."""
import json
import xml.etree.ElementTree as ET
VERSION = "CPython 3.12.14 offline Android socket/graphics/ColorMatrix verifier (Android SDK/emulator absent)"
NS = "{http://schemas.android.com/apk/res/android}"
LAYER_ONE_XML = """<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
<shape android:shape="rectangle">
<solid android:color="#C2C2C1" />
<corners android:radius="50dp" />
</shape>
</item>
<item android:id="@android:id/progress">
<clip>
<shape android:shape="rectangle">
<solid android:color="#BCDA73" />
<corners android:radius="50dp" />
</shape>
</clip>
</item>
</layer-list>"""
LAYER_TWO_XML = """<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item><bitmap android:gravity="center" android:src="@mipmap/ic_bg_ciwei" /></item>
<item android:left="25dp" android:top="25dp"><bitmap android:gravity="center" android:src="@mipmap/ic_bg_ciwei" /></item>
<item android:left="50dp" android:top="50dp"><bitmap android:gravity="center" android:src="@mipmap/ic_bg_ciwei" /></item>
</layer-list>"""
TRANSITION_XML = """<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@mipmap/ic_bg_1"/>
<item android:drawable="@mipmap/ic_bg_2"/>
</transition>"""
LEVEL_LIST_XML = """<?xml version="1.0" encoding="utf-8"?>
<level-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/shape_cir1" android:maxLevel="2000"/>
<item android:drawable="@drawable/shape_cir2" android:maxLevel="4000"/>
<item android:drawable="@drawable/shape_cir3" android:maxLevel="6000"/>
<item android:drawable="@drawable/shape_cir4" android:maxLevel="8000"/>
<item android:drawable="@drawable/shape_cir5" android:maxLevel="10000"/>
</level-list>"""
SELECTOR_XML = """<?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/shape_btn_pressed"/>
<item android:drawable="@drawable/shape_btn_normal"/>
</selector>"""
def case_layer_drawable_zorder_and_insets():
r1 = ET.fromstring(LAYER_ONE_XML)
r2 = ET.fromstring(LAYER_TWO_XML)
layer1_ids = [it.attrib[NS + "id"] for it in r1.findall("item")]
offsets = [
(int(it.attrib.get(NS + "left", "0dp").replace("dp", "")), int(it.attrib.get(NS + "top", "0dp").replace("dp", "")))
for it in r2.findall("item")
]
actual = {
"seekbar_layers_back_to_front": layer1_ids,
"stacked_layer_count": len(offsets),
"stacked_offsets_dp": [list(o) for o in offsets],
"topmost_index": len(offsets) - 1,
}
expected = {
"seekbar_layers_back_to_front": ["@android:id/background", "@android:id/progress"],
"stacked_layer_count": 3,
"stacked_offsets_dp": [[0, 0], [25, 25], [50, 50]],
"topmost_index": 2,
}
return {
"name": "layer_drawable_zorder_and_insets",
"summary": "Verify <layer-list> back-to-front draw order and per-layer offset attributes",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_transition_drawable_two_layer_alpha():
root = ET.fromstring(TRANSITION_XML)
items = root.findall("item")
duration = 3000
forward_alpha = [round(t / duration, 2) for t in (0, 1500, 3000)]
reverse_alpha = [round(1.0 - t / duration, 2) for t in (0, 1500, 3000)]
actual = {
"layer_count": len(items),
"strictly_two_layers": len(items) == 2,
"forward_top_alpha": forward_alpha,
"reverse_top_alpha": reverse_alpha,
}
expected = {
"layer_count": 2,
"strictly_two_layers": True,
"forward_top_alpha": [0.0, 0.5, 1.0],
"reverse_top_alpha": [1.0, 0.5, 0.0],
}
return {
"name": "transition_drawable_two_layer_alpha",
"summary": "Verify <transition> two-layer structure and forward/reverse alpha interpolation",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_level_list_drawable_threshold_selection():
root = ET.fromstring(LEVEL_LIST_XML)
entries = []
for it in root.findall("item"):
entries.append((int(it.attrib.get(NS + "minLevel", "0")), int(it.attrib[NS + "maxLevel"]), it.attrib[NS + "drawable"]))
def pick(level: int):
for mn, mx, dr in entries:
if mn <= level <= mx:
return dr
return None
picked = {str(lv): pick(lv) for lv in (0, 2000, 4000, 6000, 8000, 10000)}
actual = {"item_count": len(entries), "selected_by_level": picked}
expected = {
"item_count": 5,
"selected_by_level": {
"0": "@drawable/shape_cir1",
"2000": "@drawable/shape_cir1",
"4000": "@drawable/shape_cir2",
"6000": "@drawable/shape_cir3",
"8000": "@drawable/shape_cir4",
"10000": "@drawable/shape_cir5",
},
}
return {
"name": "level_list_drawable_threshold_selection",
"summary": "Verify <level-list> maxLevel threshold matching across 0..10000",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_state_list_drawable_first_match_order():
root = ET.fromstring(SELECTOR_XML)
rules = []
for it in root.findall("item"):
conds = {k.replace(NS, ""): (v == "true") for k, v in it.attrib.items() if k.startswith(NS + "state_")}
rules.append((conds, it.attrib[NS + "drawable"]))
def match(state: dict):
for conds, dr in rules:
if all(state.get(k, False) == v for k, v in conds.items()):
return dr
return None
actual = {
"pressed_state": match({"state_pressed": True}),
"normal_state": match({"state_pressed": False}),
"default_item_must_be_last": len(rules[-1][0]) == 0,
}
expected = {
"pressed_state": "@drawable/shape_btn_pressed",
"normal_state": "@drawable/shape_btn_normal",
"default_item_must_be_last": True,
}
return {
"name": "state_list_drawable_first_match_order",
"summary": "Verify <selector> top-to-bottom first-match evaluation and default-last rule",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_layer_drawable_zorder_and_insets(),
case_transition_drawable_two_layer_alpha(),
case_level_list_drawable_threshold_selection(),
case_state_list_drawable_first_match_order(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对 layer-list 图层顺序与偏移、transition 双层透明度插值、level-list 5 档阈值选择及 selector 自顶向下首次匹配。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:0b4ddbca9554502920cf92a816af88d06112f8865d5485ee80b96a1467f7b665
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:b68828c4aceafd164f59049f8a174466ae458d88d7ae751d2b1c56224c8f6465
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 StateListDrawable 的 <selector> XML 中,如果把不带任何 state_ 属性的默认 <item> 写在第一行会发生什么?
展开参考解答
Android 按从上到下的顺序选取第一个满足当前所有状态的 <item>;无状态条件的项恒为真,放在第一行会永远命中,导致后面的 state_pressed 等状态完全失效。