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

运行 GridLayout 6x4 计算器 24 格占格引擎、fill 填充规则、行列游标方向与版本兼容标签验证

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

import json
import xml.etree.ElementTree as ET

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

CALC_XML = """<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/GridLayout1" android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:columnCount="4" android:orientation="horizontal" android:rowCount="6">
    <TextView android:layout_columnSpan="4" android:layout_gravity="fill" android:text="0" android:textSize="50sp" />
    <Button android:layout_columnSpan="2" android:layout_gravity="fill" android:text="回退" />
    <Button android:layout_columnSpan="2" android:layout_gravity="fill" android:text="清空" />
    <Button android:text="+" /><Button android:text="1" /><Button android:text="2" /><Button android:text="3" />
    <Button android:text="-" /><Button android:text="4" /><Button android:text="5" /><Button android:text="6" />
    <Button android:text="*" /><Button android:text="7" /><Button android:text="8" /><Button android:text="9" />
    <Button android:text="/" /><Button android:text="." /><Button android:text="0" /><Button android:text="=" />
</GridLayout>"""


def place_grid_children(root: ET.Element) -> tuple[list[dict], int]:
    rows = int(root.attrib[f"{ANDROID_NS}rowCount"])
    cols = int(root.attrib[f"{ANDROID_NS}columnCount"])
    orient = root.attrib.get(f"{ANDROID_NS}orientation", "horizontal")
    occupied = [[False] * cols for _ in range(rows)]
    placements = []
    collisions = 0

    def next_slot(rs: int, cs: int) -> tuple[int, int]:
        if orient == "horizontal":
            for r in range(rows):
                for c in range(cols):
                    if r + rs <= rows and c + cs <= cols and all(not occupied[rr][cc] for rr in range(r, r + rs) for cc in range(c, c + cs)):
                        return r, c
        else:
            for c in range(cols):
                for r in range(rows):
                    if r + rs <= rows and c + cs <= cols and all(not occupied[rr][cc] for rr in range(r, r + rs) for cc in range(c, c + cs)):
                        return r, c
        raise RuntimeError("Grid overflow")

    for child in root:
        rs = int(child.attrib.get(f"{ANDROID_NS}layout_rowSpan", "1"))
        cs = int(child.attrib.get(f"{ANDROID_NS}layout_columnSpan", "1"))
        if f"{ANDROID_NS}layout_row" in child.attrib and f"{ANDROID_NS}layout_column" in child.attrib:
            r = int(child.attrib[f"{ANDROID_NS}layout_row"])
            c = int(child.attrib[f"{ANDROID_NS}layout_column"])
        else:
            r, c = next_slot(rs, cs)
        for rr in range(r, r + rs):
            for cc in range(c, c + cs):
                if occupied[rr][cc]:
                    collisions += 1
                occupied[rr][cc] = True
        placements.append(
            {
                "tag": child.tag,
                "text": child.attrib.get(f"{ANDROID_NS}text", ""),
                "row": r,
                "col": c,
                "row_span": rs,
                "col_span": cs,
                "gravity": child.attrib.get(f"{ANDROID_NS}layout_gravity", ""),
            }
        )
    return placements, collisions


def case_calculator_grid_occupancy() -> dict:
    root = ET.fromstring(CALC_XML)
    placements, collisions = place_grid_children(root)
    total_cells_covered = sum(p["row_span"] * p["col_span"] for p in placements)
    actual = {
        "child_count": len(placements),
        "total_cells_covered": total_cells_covered,
        "collisions": collisions,
        "display_span": [placements[0]["row"], placements[0]["col"], placements[0]["col_span"]],
        "action_row": [[p["text"], p["row"], p["col"], p["col_span"]] for p in placements[1:3]],
        "last_button": [placements[-1]["text"], placements[-1]["row"], placements[-1]["col"]],
    }
    expected = {
        "child_count": 19,
        "total_cells_covered": 24,
        "collisions": 0,
        "display_span": [0, 0, 4],
        "action_row": [["回退", 1, 0, 2], ["清空", 1, 2, 2]],
        "last_button": ["=", 5, 3],
    }
    return {
        "name": "gridlayout_calculator_cell_occupancy",
        "summary": "解析 6x4 计算器 GridLayout XML 并验证 19 个控件零冲突占满全部 24 个单元格",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_span_and_fill_gravity() -> dict:
    col_width_dp = 80
    intrinsic_btn_w = 88
    span_cols = 2
    span_total_w = col_width_dp * span_cols
    without_fill_w = intrinsic_btn_w
    with_fill_w = span_total_w
    actual = {
        "spanned_slot_width_dp": span_total_w,
        "width_without_fill_gravity_dp": without_fill_w,
        "width_with_fill_gravity_dp": with_fill_w,
        "fill_expands_to_span": with_fill_w == span_total_w > without_fill_w,
    }
    expected = {
        "spanned_slot_width_dp": 160,
        "width_without_fill_gravity_dp": 88,
        "width_with_fill_gravity_dp": 160,
        "fill_expands_to_span": True,
    }
    return {
        "name": "gridlayout_span_and_fill_gravity_rule",
        "summary": "验证跨列控件未设 layout_gravity=fill 时仅保持 wrap_content 宽,设置 fill 后填满跨列宽度",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_orientation_cursor_flow() -> dict:
    def flow(orient: str) -> list[tuple[int, int]]:
        xml = f"""<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:rowCount="2" android:columnCount="2" android:orientation="{orient}">
            <Button android:text="A"/><Button android:text="B"/>
            <Button android:text="C"/><Button android:text="D"/>
        </GridLayout>"""
        pl, _ = place_grid_children(ET.fromstring(xml))
        return [(p["row"], p["col"]) for p in pl]

    actual = {
        "horizontal_coords": [list(c) for c in flow("horizontal")],
        "vertical_coords": [list(c) for c in flow("vertical")],
    }
    expected = {
        "horizontal_coords": [[0, 0], [0, 1], [1, 0], [1, 1]],
        "vertical_coords": [[0, 0], [1, 0], [0, 1], [1, 1]],
    }
    return {
        "name": "gridlayout_orientation_cursor_flow",
        "summary": "对比 GridLayout 水平(先行后列)与垂直(先列后行)排列游标的 0 起坐标序列",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_minsdk_and_compat_tag() -> dict:
    def resolve_tag(min_sdk: int, use_androidx: bool) -> str:
        if use_androidx:
            return "androidx.gridlayout.widget.GridLayout"
        if min_sdk >= 14:
            return "GridLayout"
        return "android.support.v7.widget.GridLayout"

    actual = {
        "api_10_legacy_v7": resolve_tag(10, use_androidx=False),
        "api_14_framework": resolve_tag(14, use_androidx=False),
        "modern_androidx": resolve_tag(21, use_androidx=True),
    }
    expected = {
        "api_10_legacy_v7": "android.support.v7.widget.GridLayout",
        "api_14_framework": "GridLayout",
        "modern_androidx": "androidx.gridlayout.widget.GridLayout",
    }
    return {
        "name": "gridlayout_minsdk_and_compat_tag",
        "summary": "校验 minSdk<14 使用 v7 兼容标签、minSdk>=14 使用框架 GridLayout 及现代 AndroidX 标签演进",
        "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_calculator_grid_occupancy(),
            case_span_and_fill_gravity(),
            case_orientation_cursor_flow(),
            case_minsdk_and_compat_tag(),
        ],
    }
    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-gridlayout-lab/explore-tutorial-gridlayout.py

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

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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