"""Offline Android UI verifier for Ch 24: Button and ImageButton."""
import json
import xml.etree.ElementTree as ET
ANDROID_NS = "{http://schemas.android.com/apk/res/android}"
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/ic_course_bg_fen" />
<item android:state_enabled="false" android:drawable="@drawable/ic_course_bg_pressed" />
<item android:drawable="@drawable/ic_course_bg_cheng" />
</selector>
"""
SHADOWED_SELECTOR_XML = """<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ic_course_bg_cheng" />
<item android:state_pressed="true" android:drawable="@drawable/ic_course_bg_fen" />
</selector>
"""
ROUNDED_SELECTOR_XML = """<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"><shape>
<solid android:color="@color/bbutton_danger_pressed" />
<stroke android:width="1dp" android:color="@color/bbutton_danger_edge" />
<corners android:radius="@dimen/bbuton_rounded_corner_radius" />
</shape></item>
<item android:state_enabled="false"><shape>
<solid android:color="@color/bbutton_danger_disabled" />
<stroke android:width="1dp" android:color="@color/bbutton_danger_disabled_edge" />
<corners android:radius="@dimen/bbuton_rounded_corner_radius" />
</shape></item>
<item><shape>
<solid android:color="@color/bbutton_danger" />
<stroke android:width="1dp" android:color="@color/bbutton_danger_edge" />
<corners android:radius="@dimen/bbuton_rounded_corner_radius" />
</shape></item>
</selector>
"""
COLORS_XML = """<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="bbutton_danger_pressed">#ffd2322d</color>
<color name="bbutton_danger_edge">#ffd43f3a</color>
<color name="bbutton_danger_disabled">#a5d9534f</color>
<color name="bbutton_danger_disabled_edge">#a5d43f3a</color>
<color name="bbutton_danger">#ffd9534f</color>
<color name="text_font_white">#FFFFFF</color>
</resources>
"""
def match_selector(selector_xml: str, state: dict) -> ET.Element:
root = ET.fromstring(selector_xml)
for item in root.findall("item"):
matched = True
for k, v in item.attrib.items():
if k.startswith(f"{ANDROID_NS}state_"):
sname = k[len(ANDROID_NS):]
want = v == "true"
if bool(state.get(sname, False)) != want:
matched = False
break
if matched:
return item
raise ValueError("No matching selector item")
def count_max_radio(w: int, h: int, ex: int, ey: int) -> int:
if w > h:
return (w - ex) if ex < w // 2 else (w // 2 + ex)
return (h - ey) if ey < h // 2 else (h // 2 + ey)
def main() -> None:
# Case 1: StateListDrawable first-match evaluation
c1_actual = {
"pressed": match_selector(SELECTOR_XML, {"state_pressed": True, "state_enabled": True}).attrib[f"{ANDROID_NS}drawable"],
"disabled": match_selector(SELECTOR_XML, {"state_pressed": False, "state_enabled": False}).attrib[f"{ANDROID_NS}drawable"],
"normal": match_selector(SELECTOR_XML, {"state_pressed": False, "state_enabled": True}).attrib[f"{ANDROID_NS}drawable"],
"default_first_shadows_pressed": match_selector(SHADOWED_SELECTOR_XML, {"state_pressed": True}).attrib[f"{ANDROID_NS}drawable"],
}
c1_expected = {
"pressed": "@drawable/ic_course_bg_fen",
"disabled": "@drawable/ic_course_bg_pressed",
"normal": "@drawable/ic_course_bg_cheng",
"default_first_shadows_pressed": "@drawable/ic_course_bg_cheng",
}
# Case 2: MainActivity btnOne/btnTwo toggle state transitions
btn1_enabled = True
btn2_text = "按钮不可用"
trace = []
for _ in range(2):
if btn2_text == "按钮不可用":
btn1_enabled = False
btn2_text = "按钮可用"
else:
btn1_enabled = True
btn2_text = "按钮不可用"
bg = match_selector(SELECTOR_XML, {"state_pressed": False, "state_enabled": btn1_enabled}).attrib[f"{ANDROID_NS}drawable"]
trace.append({"btn1_enabled": btn1_enabled, "btn2_text": btn2_text, "btn1_bg": bg})
c2_expected = [
{"btn1_enabled": False, "btn2_text": "按钮可用", "btn1_bg": "@drawable/ic_course_bg_pressed"},
{"btn1_enabled": True, "btn2_text": "按钮不可用", "btn1_bg": "@drawable/ic_course_bg_cheng"},
]
# Case 3: Rounded shape selector + colors.xml resolution
colors = {el.attrib["name"]: el.text for el in ET.fromstring(COLORS_XML).findall("color")}
resolved_shapes = {}
for label, st in (
("pressed", {"state_pressed": True, "state_enabled": True}),
("disabled", {"state_pressed": False, "state_enabled": False}),
("normal", {"state_pressed": False, "state_enabled": True}),
):
shape = match_selector(ROUNDED_SELECTOR_XML, st).find("shape")
solid_ref = shape.find("solid").attrib[f"{ANDROID_NS}color"].split("/")[-1]
stroke_ref = shape.find("stroke").attrib[f"{ANDROID_NS}color"].split("/")[-1]
resolved_shapes[label] = {"solid": colors[solid_ref], "stroke": colors[stroke_ref]}
c3_expected = {
"pressed": {"solid": "#ffd2322d", "stroke": "#ffd43f3a"},
"disabled": {"solid": "#a5d9534f", "stroke": "#a5d43f3a"},
"normal": {"solid": "#ffd9534f", "stroke": "#ffd43f3a"},
}
# Case 4: Custom ripple MyButton radius math & short-tap vs long-press stepping
max_r_wide = count_max_radio(300, 64, 80, 32) # 300 - 80 = 220
max_r_tall = count_max_radio(64, 200, 32, 120) # 100 + 120 = 220
# Short tap (< 500ms): 2 frames at gap=10, then accelerates to gap=30 until >= 220
r = 0
frames_short = 0
gap = 10
while r < max_r_wide:
frames_short += 1
r += gap
if frames_short == 2:
gap = 30
c4_actual = {
"max_radio_wide": max_r_wide,
"max_radio_tall": max_r_tall,
"short_tap_frames": frames_short,
"final_radius": r,
}
c4_expected = {
"max_radio_wide": 220,
"max_radio_tall": 220,
"short_tap_frames": 9,
"final_radius": 230,
}
cases = [
{
"name": "selector_state_list_first_match",
"summary": "验证 StateListDrawable 按从上到下首个匹配规则解析按下/禁用/默认状态及默认项置顶遮蔽风险",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "toggle_button_enabled_interaction",
"summary": "模拟两按钮联动切换 setEnabled(false/true) 后的背景状态转移",
"expected": c2_expected,
"actual": trace,
"passed": trace == c2_expected,
},
{
"name": "rounded_shape_selector_and_resources",
"summary": "解析 selector 内嵌 shape 圆角按钮资源并联动 colors.xml 计算三态色值",
"expected": c3_expected,
"actual": resolved_shapes,
"passed": resolved_shapes == c3_expected,
},
{
"name": "ripple_radius_and_tap_vs_longpress",
"summary": "核算自定义水波纹 MyButton 最大扩散半径与短按加速步进帧数",
"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-button-imagebutton-lab/explore-tutorial-button-imagebutton.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial-button-imagebutton.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1850.zip