"""Offline Android system-service verifier for Ch 143: LayoutInflater."""
from dataclasses import dataclass, field
import json
import xml.etree.ElementTree as ET
VERSION = (
"CPython 3.12.14 offline Android system-service/sensor/capstone verifier "
"(Android SDK/emulator absent)"
)
ANDROID_NS = "{http://schemas.android.com/apk/res/android}"
@dataclass
class ViewNode:
tag: str
view_id: str | None = None
layout_params: dict[str, str] | None = None
rules: list[tuple[str, int | None]] = field(default_factory=list)
children: list["ViewNode"] = field(default_factory=list)
def generate_layout_params(self, attrs: dict[str, str]) -> dict[str, str]:
lp = {"parent_type": self.tag}
for k, v in attrs.items():
short = k.replace(ANDROID_NS, "")
if short.startswith("layout_"):
lp[short] = v
return lp
def add_view(self, child: "ViewNode", params: dict[str, str] | None = None) -> None:
if params is not None:
child.layout_params = params
self.children.append(child)
def inflate_xml(xml_str: str, root: ViewNode | None, attach_to_root: bool) -> ViewNode:
el = ET.fromstring(xml_str)
if el.tag == "merge":
if root is None or not attach_to_root:
raise ValueError("InflateException: merge can be used only with a valid ViewGroup root and attachToRoot=true")
for sub in el:
child = _build_node(sub, parent=root)
root.add_view(child, root.generate_layout_params(sub.attrib))
return root
temp = _build_node(el, parent=None)
params = None
if root is not None:
params = root.generate_layout_params(el.attrib)
if not attach_to_root:
temp.layout_params = params
if root is not None and attach_to_root:
root.add_view(temp, params)
return root
return temp
def _build_node(el: ET.Element, parent: ViewNode | None) -> ViewNode:
vid = el.attrib.get(f"{ANDROID_NS}id")
node = ViewNode(tag=el.tag, view_id=vid)
for sub in el:
child = _build_node(sub, parent=node)
child.layout_params = node.generate_layout_params(sub.attrib)
node.children.append(child)
return node
INFLATE_CHILD_XML = """<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ly_inflate"
android:layout_width="240dp"
android:layout_height="120dp"
android:layout_marginTop="16dp"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="动态加载文本" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="内部按钮" />
</LinearLayout>
"""
MERGE_XML = """<merge xmlns:android="http://schemas.android.com/apk/res/android">
<TextView android:id="@+id/m1" android:layout_width="wrap_content" android:layout_height="wrap_content" />
<Button android:id="@+id/m2" android:layout_width="wrap_content" android:layout_height="wrap_content" />
</merge>"""
def main() -> None:
# Case 1: LayoutInflater.inflate(res, root, attachToRoot) 3-branch matrix + <merge> guard
res_null = inflate_xml(INFLATE_CHILD_XML, root=None, attach_to_root=False)
parent_false = ViewNode(tag="RelativeLayout", view_id="@+id/RelativeLayout1")
res_false = inflate_xml(INFLATE_CHILD_XML, root=parent_false, attach_to_root=False)
parent_true = ViewNode(tag="RelativeLayout", view_id="@+id/RelativeLayout1")
res_true = inflate_xml(INFLATE_CHILD_XML, root=parent_true, attach_to_root=True)
merge_err_null = False
try:
inflate_xml(MERGE_XML, root=None, attach_to_root=False)
except ValueError:
merge_err_null = True
merge_err_false = False
try:
inflate_xml(MERGE_XML, root=ViewNode("FrameLayout"), attach_to_root=False)
except ValueError:
merge_err_false = True
merge_parent = ViewNode("FrameLayout")
merge_ok = inflate_xml(MERGE_XML, root=merge_parent, attach_to_root=True)
c1_actual = {
"branch_root_null": {
"returned_tag": res_null.tag,
"root_layout_params_preserved": res_null.layout_params is not None,
"child_count": len(res_null.children),
},
"branch_root_attach_false": {
"returned_is_child": res_false is not parent_false,
"returned_tag": res_false.tag,
"attached_to_root": len(parent_false.children) > 0,
"root_layout_params_preserved": res_false.layout_params is not None,
"width_preserved": res_false.layout_params["layout_width"] if res_false.layout_params else None,
"margin_top_preserved": res_false.layout_params["layout_marginTop"] if res_false.layout_params else None,
},
"branch_root_attach_true": {
"returned_is_root": res_true is parent_true,
"root_child_count": len(parent_true.children),
"attached_child_tag": parent_true.children[0].tag,
"attached_width": parent_true.children[0].layout_params["layout_width"],
},
"merge_rules": {
"throws_when_root_null": merge_err_null,
"throws_when_attach_false": merge_err_false,
"flattens_into_parent_when_true": len(merge_ok.children),
},
}
c1_expected = {
"branch_root_null": {
"returned_tag": "LinearLayout",
"root_layout_params_preserved": False,
"child_count": 2,
},
"branch_root_attach_false": {
"returned_is_child": True,
"returned_tag": "LinearLayout",
"attached_to_root": False,
"root_layout_params_preserved": True,
"width_preserved": "240dp",
"margin_top_preserved": "16dp",
},
"branch_root_attach_true": {
"returned_is_root": True,
"root_child_count": 1,
"attached_child_tag": "LinearLayout",
"attached_width": "240dp",
},
"merge_rules": {
"throws_when_root_null": True,
"throws_when_attach_false": True,
"flattens_into_parent_when_true": 2,
},
}
# Case 2: Pure Java RelativeLayout construction + addRule rules & manual ID reference
rly = ViewNode(tag="RelativeLayout")
btn_one = ViewNode(tag="Button", view_id="123", rules=[("CENTER_IN_PARENT", None)])
btn_two = ViewNode(
tag="Button",
view_id=None,
rules=[("BELOW", 123), ("ALIGN_PARENT_RIGHT", None)],
)
rly.add_view(btn_two, {"layout_width": "wrap_content", "layout_height": "wrap_content"})
rly.add_view(btn_one, {"layout_width": "wrap_content", "layout_height": "wrap_content"})
c2_actual = {
"container": rly.tag,
"child_count": len(rly.children),
"btn_two_below_target": btn_two.rules[0][1],
"btn_one_id": int(btn_one.view_id),
"id_matches_target": int(btn_one.view_id) == btn_two.rules[0][1],
}
c2_expected = {
"container": "RelativeLayout",
"child_count": 2,
"btn_two_below_target": 123,
"btn_one_id": 123,
"id_matches_target": True,
}
# Case 3: Dynamic View addition (pre-setContentView vs post-setContentView) & dynamic XML load
main_xml = """<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button android:id="@+id/btnLoad" android:layout_width="match_parent" android:layout_height="wrap_content" />
</RelativeLayout>"""
root_view = inflate_xml(main_xml, root=None, attach_to_root=False)
# Path A: add a dynamic Button
dyn_btn = ViewNode(tag="Button", view_id="dyn_btn", rules=[("CENTER_IN_PARENT", None)])
root_view.add_view(dyn_btn, {"layout_width": "wrap_content", "layout_height": "wrap_content"})
# Path B: inflate inflate.xml and attach with explicit RelativeLayout.LayoutParams
sub_ly = inflate_xml(INFLATE_CHILD_XML, root=None, attach_to_root=False)
root_view.add_view(sub_ly, {"layout_width": "wrap_content", "layout_height": "wrap_content", "rule": "CENTER_IN_PARENT"})
c3_actual = {
"root_id": root_view.view_id,
"total_children_after_dynamic_adds": len(root_view.children),
"child_tags": [c.tag for c in root_view.children],
"nested_inflate_children": len(sub_ly.children),
}
c3_expected = {
"root_id": "@+id/RelativeLayout1",
"total_children_after_dynamic_adds": 3,
"child_tags": ["Button", "Button", "LinearLayout"],
"nested_inflate_children": 2,
}
cases = [
{
"name": "layoutinflater_three_branch_and_merge_matrix",
"summary": "验证 inflate(res, root, attachToRoot) 三分支返回值与 LayoutParams 保留规则及 <merge> 约束",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "pure_java_relativelayout_addrule",
"summary": "验证纯 Java 代码创建 RelativeLayout、手动设置参照控件 ID 与 addRule 相对定位规则",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
{
"name": "dynamic_addview_and_xml_inflation",
"summary": "验证动态添加 Button 与点击后按需 inflate 子布局 XML 并挂载到主容器的视图树结果",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
},
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/android-tutorial-layoutinflater-lab/explore-tutorial-layoutinflater.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial-layoutinflater.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1911.zip