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

运行离线 ToggleButton/Switch 属性解析、thumb/track 四态组合与事件分发核验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-togglebutton-switch.py
explore-tutorial-togglebutton-switch.py156 行
"""Offline Android UI verifier for Ch 27: ToggleButton and Switch."""
import json
import xml.etree.ElementTree as ET

ANDROID_NS = "{http://schemas.android.com/apk/res/android}"

LAYOUT_XML = """<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical">
    <ToggleButton
        android:id="@+id/tbtn_open"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:disabledAlpha="0.5"
        android:textOff="关闭声音"
        android:textOn="打开声音" />
    <Switch
        android:id="@+id/swh_status"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:showText="false"
        android:splitTrack="false"
        android:switchMinWidth="48dp"
        android:switchPadding="8dp"
        android:textOff=""
        android:textOn=""
        android:thumb="@drawable/thumb_selctor"
        android:track="@drawable/track_selctor" />
</LinearLayout>
"""

THUMB_SELECTOR_XML = """<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/switch_btn_pressed" />
    <item android:state_pressed="false" android:drawable="@drawable/switch_btn_normal" />
</selector>
"""

TRACK_SELECTOR_XML = """<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:drawable="@drawable/switch_btn_bg_green" />
    <item android:state_checked="false" android:drawable="@drawable/switch_btn_bg_white" />
</selector>
"""


def eval_selector(xml_str: str, state_key: str, val: bool) -> str:
    root = ET.fromstring(xml_str)
    for item in root.findall("item"):
        if (item.attrib[f"{ANDROID_NS}{state_key}"] == "true") == val:
            return item.attrib[f"{ANDROID_NS}drawable"]
    return ""


def main() -> None:
    root = ET.fromstring(LAYOUT_XML)
    tbtn, swh = root[0], root[1]
    c1_actual = {
        "toggle_checked": tbtn.attrib[f"{ANDROID_NS}checked"] == "true",
        "toggle_labels": [tbtn.attrib[f"{ANDROID_NS}textOff"], tbtn.attrib[f"{ANDROID_NS}textOn"]],
        "toggle_disabled_alpha": float(tbtn.attrib[f"{ANDROID_NS}disabledAlpha"]),
        "switch_min_api": 14,
        "switch_custom_drawables": [swh.attrib[f"{ANDROID_NS}thumb"], swh.attrib[f"{ANDROID_NS}track"]],
    }
    c1_expected = {
        "toggle_checked": True,
        "toggle_labels": ["关闭声音", "打开声音"],
        "toggle_disabled_alpha": 0.5,
        "switch_min_api": 14,
        "switch_custom_drawables": ["@drawable/thumb_selctor", "@drawable/track_selctor"],
    }

    # Case 2: All 4 (pressed, checked) drawable combinations for Switch
    combos = {}
    for pressed in (False, True):
        for checked in (False, True):
            combos[f"pressed={int(pressed)}_checked={int(checked)}"] = {
                "thumb": eval_selector(THUMB_SELECTOR_XML, "state_pressed", pressed),
                "track": eval_selector(TRACK_SELECTOR_XML, "state_checked", checked),
            }
    c2_expected = {
        "pressed=0_checked=0": {"thumb": "@drawable/switch_btn_normal", "track": "@drawable/switch_btn_bg_white"},
        "pressed=0_checked=1": {"thumb": "@drawable/switch_btn_normal", "track": "@drawable/switch_btn_bg_green"},
        "pressed=1_checked=0": {"thumb": "@drawable/switch_btn_pressed", "track": "@drawable/switch_btn_bg_white"},
        "pressed=1_checked=1": {"thumb": "@drawable/switch_btn_pressed", "track": "@drawable/switch_btn_bg_green"},
    }

    # Case 3: CompoundButton.OnCheckedChangeListener dispatch (fixing else branch message)
    def dispatch(widget_id: str, checked: bool) -> str:
        if widget_id == "tbtn_open":
            return "打开声音" if checked else "关闭声音"
        if widget_id == "swh_status":
            return "开关:ON" if checked else "开关:OFF"
        return ""

    c3_actual = [
        dispatch("tbtn_open", False),
        dispatch("tbtn_open", True),
        dispatch("swh_status", True),
        dispatch("swh_status", False),
    ]
    c3_expected = ["关闭声音", "打开声音", "开关:ON", "开关:OFF"]

    # Case 4: Typeface built-ins & custom asset font path validation
    builtin_typefaces = ["sans", "serif", "monospace"]
    custom_font = "fonts/HandmadeTypewriter.ttf"
    c4_actual = {
        "builtins": builtin_typefaces,
        "asset_relative_path": custom_font,
        "full_assets_path": f"assets/{custom_font}",
        "is_ttf": custom_font.endswith(".ttf"),
    }
    c4_expected = {
        "builtins": ["sans", "serif", "monospace"],
        "asset_relative_path": "fonts/HandmadeTypewriter.ttf",
        "full_assets_path": "assets/fonts/HandmadeTypewriter.ttf",
        "is_ttf": True,
    }

    cases = [
        {
            "name": "togglebutton_switch_xml_and_minsdk",
            "summary": "解析 ToggleButton 与 Switch XML 核心属性并核对 Switch 的 API 14 最低版本约束",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "switch_thumb_and_track_selectors",
            "summary": "验证滑块 thumb(state_pressed) 与轨道 track(state_checked) 四个状态组合解析",
            "expected": c2_expected,
            "actual": combos,
            "passed": combos == c2_expected,
        },
        {
            "name": "checked_change_listener_dispatch",
            "summary": "模拟 OnCheckedChangeListener 双向切换分发并修正关闭状态文案",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        },
        {
            "name": "typeface_asset_path_resolution",
            "summary": "核对系统默认字体族(sans/serif/monospace)及 assets/fonts 外部字体路径规范",
            "expected": c4_expected,
            "actual": c4_actual,
            "passed": c4_actual == c4_expected,
        },
    ]
    print(json.dumps({
        "version": "CPython 3.12.14 offline Android UI/XML/Adapter verifier (Android SDK/emulator absent)",
        "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-togglebutton-switch-lab/explore-tutorial-togglebutton-switch.py

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

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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