蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

验证 Layer/Transition/LevelList/StateList 四类 Drawable XML 解析与匹配规则

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-drawable3.py
explore-tutorial-drawable3.py189 行
"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/android-tutorial-drawable3-lab/explore-tutorial-drawable3.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-tutorial-drawable3.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Android

课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip

下载课程关联工程包:Android

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1874.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习