"""Offline Android UI verifier for Ch 26: RadioButton and CheckBox."""
from dataclasses import dataclass
import json
import xml.etree.ElementTree as ET
ANDROID_NS = "{http://schemas.android.com/apk/res/android}"
RADIO_GROUP_XML = """<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton android:id="@+id/btnMan" android:text="男" android:checked="true" />
<RadioButton android:id="@+id/btnWoman" android:text="女" />
</RadioGroup>
"""
CHECKBOX_SELECTOR_XML = """<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="true" android:state_checked="true" android:drawable="@mipmap/ic_checkbox_checked" />
<item android:state_enabled="true" android:state_checked="false" android:drawable="@mipmap/ic_checkbox_normal" />
</selector>
"""
STYLE_XML = """<resources>
<style name="MyCheckBox" parent="@android:style/Widget.CompoundButton.CheckBox">
<item name="android:button">@drawable/rad_btn_selctor</item>
</style>
</resources>
"""
@dataclass
class RadioBtn:
rid: str
text: str
checked: bool = False
class RadioGroupModel:
def __init__(self, buttons: list):
self.buttons = buttons
self.events = []
def check(self, target_id: str) -> None:
if not target_id:
return
for b in self.buttons:
b.checked = (b.rid == target_id)
selected = next((b.text for b in self.buttons if b.checked), None)
self.events.append({"checkedId": target_id, "text": selected})
def get_checked_via_loop(self) -> str:
for i in range(len(self.buttons)):
if self.buttons[i].checked:
return self.buttons[i].text
return ""
def main() -> None:
rg_xml = ET.fromstring(RADIO_GROUP_XML)
btns = []
for ch in rg_xml:
btns.append(RadioBtn(
rid=ch.attrib.get(f"{ANDROID_NS}id", "").split("/")[-1],
text=ch.attrib[f"{ANDROID_NS}text"],
checked=ch.attrib.get(f"{ANDROID_NS}checked") == "true",
))
rg = RadioGroupModel(btns)
initial_selected = rg.get_checked_via_loop()
rg.check("btnWoman")
after_switch = rg.get_checked_via_loop()
checked_count = sum(1 for b in rg.buttons if b.checked)
c1_actual = {
"orientation": rg_xml.attrib[f"{ANDROID_NS}orientation"],
"all_have_id": all(bool(b.rid) for b in rg.buttons),
"initial_selected": initial_selected,
"after_switch": after_switch,
"mutually_exclusive_count": checked_count,
"listener_events": rg.events,
}
c1_expected = {
"orientation": "horizontal",
"all_have_id": True,
"initial_selected": "男",
"after_switch": "女",
"mutually_exclusive_count": 1,
"listener_events": [{"checkedId": "btnWoman", "text": "女"}],
}
# Case 2: CheckBox multi-select & submit
cbs = {"cb_one": ["苹果", False], "cb_two": ["香蕉", False], "cb_three": ["橙子", False]}
toasts = []
for cid, state in (("cb_one", True), ("cb_three", True), ("cb_one", False), ("cb_two", True)):
cbs[cid][1] = state
if state:
toasts.append(cbs[cid][0])
submitted = [label for label, chk in cbs.values() if chk]
c2_actual = {"change_toasts": toasts, "submitted_checked": submitted}
c2_expected = {"change_toasts": ["苹果", "橙子", "香蕉"], "submitted_checked": ["香蕉", "橙子"]}
# Case 3: Custom selector & style resolution
sel_root = ET.fromstring(CHECKBOX_SELECTOR_XML)
def pick(checked: bool) -> str:
for item in sel_root.findall("item"):
if item.attrib[f"{ANDROID_NS}state_enabled"] == "true" and (item.attrib[f"{ANDROID_NS}state_checked"] == "true") == checked:
return item.attrib[f"{ANDROID_NS}drawable"]
return ""
st_node = ET.fromstring(STYLE_XML).find("style")
c3_actual = {
"checked_drawable": pick(True),
"unchecked_drawable": pick(False),
"style_name": st_node.attrib["name"],
"style_button_item": st_node.find("item").text,
}
c3_expected = {
"checked_drawable": "@mipmap/ic_checkbox_checked",
"unchecked_drawable": "@mipmap/ic_checkbox_normal",
"style_name": "MyCheckBox",
"style_button_item": "@drawable/rad_btn_selctor",
}
# Case 4: Repositioning box (button=@null + drawableTop) & dynamic paddingLeft
intrinsic_width_px = 42
padding_left = intrinsic_width_px + 5
c4_actual = {
"reposition_button_attr": "@null",
"reposition_drawable_attr": "android:drawableTop",
"computed_padding_left_px": padding_left,
}
c4_expected = {
"reposition_button_attr": "@null",
"reposition_drawable_attr": "android:drawableTop",
"computed_padding_left_px": 47,
}
cases = [
{
"name": "radiogroup_mutual_exclusion_and_id_guard",
"summary": "验证 RadioGroup 单选互斥、唯一 ID 约束、监听回调与遍历 getChildAt/isChecked 读取",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "checkbox_multiselect_and_submit",
"summary": "模拟多选 CheckBox 独立状态切换、单选回调记录与提交按钮聚合读取",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
{
"name": "custom_selector_and_style_resolution",
"summary": "解析自定义 CheckBox selector 双态资源与 style 样式绑定",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
},
{
"name": "drawable_reposition_and_dynamic_padding",
"summary": "验证 android:button=@null + drawableTop 改变选择框方位与动态计算 paddingLeft",
"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-radiobutton-checkbox-lab/explore-tutorial-radiobutton-checkbox.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial-radiobutton-checkbox.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1930.zip