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

运行 View/ViewGroup XML 视图树解析、继承关系判定、嵌套深度审计与代码构建等价性验证

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-view-viewgroup-intro.py
explore-tutorial-view-viewgroup-intro.py204 行
"""Offline deterministic verifier for Android CH15 (tutorial-view-viewgroup-intro)."""
from __future__ import annotations

import json
import xml.etree.ElementTree as ET

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

SAMPLE_XML = """<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation="vertical" >
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="I am a TextView" />
    <Button android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="I am a Button" />
</LinearLayout>"""


def case_xml_hierarchy_parser() -> dict:
    root = ET.fromstring(SAMPLE_XML)
    children = [
        {
            "tag": c.tag,
            "id": c.attrib.get(f"{ANDROID_NS}id"),
            "width": c.attrib.get(f"{ANDROID_NS}layout_width"),
            "text": c.attrib.get(f"{ANDROID_NS}text"),
        }
        for c in root
    ]
    actual = {
        "root_tag": root.tag,
        "orientation": root.attrib.get(f"{ANDROID_NS}orientation"),
        "child_count": len(children),
        "children": children,
    }
    expected = {
        "root_tag": "LinearLayout",
        "orientation": "vertical",
        "child_count": 2,
        "children": [
            {"tag": "TextView", "id": "@+id/text", "width": "wrap_content", "text": "I am a TextView"},
            {"tag": "Button", "id": "@+id/button", "width": "wrap_content", "text": "I am a Button"},
        ],
    }
    return {
        "name": "xml_view_hierarchy_tree_parser",
        "summary": "解析本节垂直 LinearLayout XML 布局树并核验 TextView 与 Button 节点 ID 和属性",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_view_viewgroup_hierarchy() -> dict:
    parent_of = {
        "View": None,
        "TextView": "View",
        "Button": "TextView",
        "EditText": "TextView",
        "ImageView": "View",
        "ViewGroup": "View",
        "LinearLayout": "ViewGroup",
        "RelativeLayout": "ViewGroup",
        "FrameLayout": "ViewGroup",
        "ConstraintLayout": "ViewGroup",
    }

    def is_subclass(cls: str, base: str) -> bool:
        cur = cls
        while cur is not None:
            if cur == base:
                return True
            cur = parent_of[cur]
        return False

    actual = {
        "viewgroup_is_view": is_subclass("ViewGroup", "View"),
        "button_is_view": is_subclass("Button", "View"),
        "button_is_viewgroup": is_subclass("Button", "ViewGroup"),
        "linearlayout_is_viewgroup": is_subclass("LinearLayout", "ViewGroup"),
        "constraintlayout_is_viewgroup": is_subclass("ConstraintLayout", "ViewGroup"),
    }
    expected = {
        "viewgroup_is_view": True,
        "button_is_view": True,
        "button_is_viewgroup": False,
        "linearlayout_is_viewgroup": True,
        "constraintlayout_is_viewgroup": True,
    }
    return {
        "name": "view_vs_viewgroup_class_hierarchy",
        "summary": "验证 Android 组合模式继承树:ViewGroup 继承自 View,容器与叶子控件共享基类",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_nesting_depth_audit() -> dict:
    def measure_depth(node: dict) -> int:
        if not node.get("children"):
            return 1
        return 1 + max(measure_depth(c) for c in node["children"])

    def count_nodes(node: dict) -> int:
        return 1 + sum(count_nodes(c) for c in node.get("children", []))

    deep_tree = {
        "tag": "LinearLayout",
        "children": [
            {
                "tag": "LinearLayout",
                "children": [
                    {
                        "tag": "LinearLayout",
                        "children": [
                            {"tag": "TextView", "children": []},
                            {"tag": "Button", "children": []},
                        ],
                    }
                ],
            }
        ],
    }
    flat_tree = {
        "tag": "LinearLayout",
        "children": [
            {"tag": "TextView", "children": []},
            {"tag": "Button", "children": []},
        ],
    }
    actual = {
        "deep_depth": measure_depth(deep_tree),
        "flat_depth": measure_depth(flat_tree),
        "deep_node_count": count_nodes(deep_tree),
        "flat_node_count": count_nodes(flat_tree),
        "flat_reduces_overhead": count_nodes(flat_tree) < count_nodes(deep_tree) and measure_depth(flat_tree) < measure_depth(deep_tree),
    }
    expected = {
        "deep_depth": 4,
        "flat_depth": 2,
        "deep_node_count": 5,
        "flat_node_count": 3,
        "flat_reduces_overhead": True,
    }
    return {
        "name": "layout_nesting_depth_performance_audit",
        "summary": "对比冗余嵌套布局树与扁平布局树的深度和节点数,验证扁平层次更利于渲染性能",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_xml_vs_programmatic_equivalence() -> dict:
    xml_root = ET.fromstring(SAMPLE_XML)
    xml_tree = (
        xml_root.tag,
        [(c.tag, c.attrib[f"{ANDROID_NS}id"], c.attrib[f"{ANDROID_NS}text"]) for c in xml_root],
    )
    # Equivalent programmatic construction via addView()
    prog_children = []
    prog_children.append(("TextView", "@+id/text", "I am a TextView"))
    prog_children.append(("Button", "@+id/button", "I am a Button"))
    prog_tree = ("LinearLayout", prog_children)
    actual = {
        "trees_equivalent": xml_tree == prog_tree,
        "instantiated_ids": [c[1] for c in prog_children],
    }
    expected = {
        "trees_equivalent": True,
        "instantiated_ids": ["@+id/text", "@+id/button"],
    }
    return {
        "name": "xml_inflation_and_programmatic_equivalence",
        "summary": "验证 XML 布局加载实例化与代码动态 addView 构造出等价的视图树结构",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main() -> None:
    payload = {
        "version": "CPython 3.12.14 offline Android XML/layout/manifest verifier (Android SDK/emulator absent)",
        "cases": [
            case_xml_hierarchy_parser(),
            case_view_viewgroup_hierarchy(),
            case_nesting_depth_audit(),
            case_xml_vs_programmatic_equivalence(),
        ],
    }
    print(json.dumps(payload, 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-view-viewgroup-intro-lab/explore-tutorial-view-viewgroup-intro.py

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

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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