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

运行 RelativeLayout 梅花布局几何求解、兄弟作用域检查、margin/padding 盒模型与负值边距越界计算

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

import json
import xml.etree.ElementTree as ET

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


def parse_dp(val: str) -> int:
    return int(val.replace("dp", ""))


def strip_id(ref: str) -> str:
    return ref.split("/", 1)[1]


def case_plum_blossom_geometry() -> dict:
    xml_text = """<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/RelativeLayout1" android:layout_width="match_parent" android:layout_height="match_parent">
        <ImageView android:id="@+id/img1" android:layout_width="80dp" android:layout_height="80dp" android:layout_centerInParent="true" />
        <ImageView android:id="@+id/img2" android:layout_width="80dp" android:layout_height="80dp" android:layout_toLeftOf="@id/img1" android:layout_centerVertical="true" />
        <ImageView android:id="@+id/img3" android:layout_width="80dp" android:layout_height="80dp" android:layout_toRightOf="@id/img1" android:layout_centerVertical="true" />
        <ImageView android:id="@+id/img4" android:layout_width="80dp" android:layout_height="80dp" android:layout_above="@id/img1" android:layout_centerHorizontal="true" />
        <ImageView android:id="@+id/img5" android:layout_width="80dp" android:layout_height="80dp" android:layout_below="@id/img1" android:layout_centerHorizontal="true" />
    </RelativeLayout>"""
    root = ET.fromstring(xml_text)
    pw, ph = 400, 400
    boxes: dict[str, list[int]] = {}
    for el in root:
        vid = strip_id(el.attrib[f"{ANDROID_NS}id"])
        w = parse_dp(el.attrib[f"{ANDROID_NS}layout_width"])
        h = parse_dp(el.attrib[f"{ANDROID_NS}layout_height"])
        left = 0
        top = 0
        if el.attrib.get(f"{ANDROID_NS}layout_centerInParent") == "true":
            left = (pw - w) // 2
            top = (ph - h) // 2
        if el.attrib.get(f"{ANDROID_NS}layout_centerHorizontal") == "true":
            left = (pw - w) // 2
        if el.attrib.get(f"{ANDROID_NS}layout_centerVertical") == "true":
            top = (ph - h) // 2
        if f"{ANDROID_NS}layout_toLeftOf" in el.attrib:
            ref = boxes[strip_id(el.attrib[f"{ANDROID_NS}layout_toLeftOf"])]
            left = ref[0] - w
        if f"{ANDROID_NS}layout_toRightOf" in el.attrib:
            ref = boxes[strip_id(el.attrib[f"{ANDROID_NS}layout_toRightOf"])]
            left = ref[2]
        if f"{ANDROID_NS}layout_above" in el.attrib:
            ref = boxes[strip_id(el.attrib[f"{ANDROID_NS}layout_above"])]
            top = ref[1] - h
        if f"{ANDROID_NS}layout_below" in el.attrib:
            ref = boxes[strip_id(el.attrib[f"{ANDROID_NS}layout_below"])]
            top = ref[3]
        boxes[vid] = [left, top, left + w, top + h]

    overlaps = 0
    ids = list(boxes)
    for i in range(len(ids)):
        for j in range(i + 1, len(ids)):
            a, b = boxes[ids[i]], boxes[ids[j]]
            if not (a[2] <= b[0] or b[2] <= a[0] or a[3] <= b[1] or b[3] <= a[1]):
                overlaps += 1
    actual = {"boxes": boxes, "overlap_count": overlaps}
    expected = {
        "boxes": {
            "img1": [160, 160, 240, 240],
            "img2": [80, 160, 160, 240],
            "img3": [240, 160, 320, 240],
            "img4": [160, 80, 240, 160],
            "img5": [160, 240, 240, 320],
        },
        "overlap_count": 0,
    }
    return {
        "name": "relativelayout_plum_blossom_geometry",
        "summary": "解析梅花布局 5 个 ImageView 相对约束并在 400x400dp 容器中求解零重叠几何坐标",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_sibling_scope_validation() -> dict:
    # comp1 and comp2 are direct children of root; comp3 is nested inside child_container
    parent_map = {
        "comp1": "root_rl",
        "comp2": "root_rl",
        "child_container": "root_rl",
        "comp3": "child_container",
    }

    def can_reference(src: str, target: str) -> bool:
        return src != target and parent_map.get(src) == parent_map.get(target)

    actual = {
        "comp2_refs_comp1_valid": can_reference("comp2", "comp1"),
        "comp3_refs_comp1_invalid": not can_reference("comp3", "comp1"),
        "self_ref_invalid": not can_reference("comp1", "comp1"),
    }
    expected = {
        "comp2_refs_comp1_valid": True,
        "comp3_refs_comp1_invalid": True,
        "self_ref_invalid": True,
    }
    return {
        "name": "relativelayout_sibling_scope_validation",
        "summary": "校验 RelativeLayout 同层兄弟组件定位作用域,拦截跨容器引用错误",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_margin_vs_padding() -> dict:
    xml_text = """<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent" android:layout_height="match_parent">
        <Button android:id="@+id/btn1" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Button"/>
        <Button android:paddingLeft="100dp" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Button" android:layout_toRightOf="@id/btn1"/>
        <Button android:id="@+id/btn2" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Button" android:layout_alignParentBottom="true"/>
        <Button android:layout_marginLeft="100dp" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Button" android:layout_toRightOf="@id/btn2" android:layout_alignParentBottom="true"/>
    </RelativeLayout>"""
    root = ET.fromstring(xml_text)
    btns = list(root)
    base_w = 88
    pad_left = parse_dp(btns[1].attrib[f"{ANDROID_NS}paddingLeft"])
    margin_left = parse_dp(btns[3].attrib[f"{ANDROID_NS}layout_marginLeft"])
    # Button with paddingLeft=100dp starts directly at x=base_w, outer width expands to base_w+100
    btn_pad_outer = [base_w, base_w + base_w + pad_left]
    btn_pad_text_start = base_w + pad_left
    # Button with layout_marginLeft=100dp shifts outer left to base_w+100, outer width remains base_w
    btn_margin_outer = [base_w + margin_left, base_w + margin_left + base_w]
    actual = {
        "padding_btn_outer_x": btn_pad_outer,
        "padding_btn_text_x": btn_pad_text_start,
        "margin_btn_outer_x": btn_margin_outer,
        "external_gap_padding_vs_margin": [btn_pad_outer[0] - base_w, btn_margin_outer[0] - base_w],
    }
    expected = {
        "padding_btn_outer_x": [88, 276],
        "padding_btn_text_x": 188,
        "margin_btn_outer_x": [188, 276],
        "external_gap_padding_vs_margin": [0, 100],
    }
    return {
        "name": "margin_vs_padding_box_model",
        "summary": "量化对比 paddingLeft=100dp(扩展控件内部填充)与 layout_marginLeft=100dp(外部间距偏移)",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_negative_margin_overlay() -> dict:
    xml_text = """<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent" android:layout_height="match_parent">
        <ImageView android:id="@+id/imgBack" android:layout_width="200dp" android:layout_height="200dp" android:layout_centerInParent="true" />
        <ImageView android:id="@+id/imgCancle" android:layout_width="28dp" android:layout_height="28dp"
            android:layout_alignRight="@id/imgBack" android:layout_alignTop="@id/imgBack"
            android:layout_marginTop="-15dp" android:layout_marginRight="-10dp" />
    </RelativeLayout>"""
    root = ET.fromstring(xml_text)
    pw, ph = 400, 400
    back_el, cancel_el = list(root)
    bw = parse_dp(back_el.attrib[f"{ANDROID_NS}layout_width"])
    bh = parse_dp(back_el.attrib[f"{ANDROID_NS}layout_height"])
    back_box = [(pw - bw) // 2, (ph - bh) // 2, (pw + bw) // 2, (ph + bh) // 2]

    cw = parse_dp(cancel_el.attrib[f"{ANDROID_NS}layout_width"])
    ch = parse_dp(cancel_el.attrib[f"{ANDROID_NS}layout_height"])
    mt = parse_dp(cancel_el.attrib[f"{ANDROID_NS}layout_marginTop"])
    mr = parse_dp(cancel_el.attrib[f"{ANDROID_NS}layout_marginRight"])
    # alignRight means right edge = back_box[2] - marginRight; alignTop means top edge = back_box[1] + marginTop
    c_right = back_box[2] - mr
    c_left = c_right - cw
    c_top = back_box[1] + mt
    c_bottom = c_top + ch
    actual = {
        "imgBack_box": back_box,
        "imgCancle_box": [c_left, c_top, c_right, c_bottom],
        "protrudes_top_dp": back_box[1] - c_top,
        "protrudes_right_dp": c_right - back_box[2],
    }
    expected = {
        "imgBack_box": [100, 100, 300, 300],
        "imgCancle_box": [282, 85, 310, 113],
        "protrudes_top_dp": 15,
        "protrudes_right_dp": 10,
    }
    return {
        "name": "negative_margin_corner_overlay",
        "summary": "解析负值 marginTop=-15dp/marginRight=-10dp 广告弹窗关闭角标的越界悬浮几何坐标",
        "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_plum_blossom_geometry(),
            case_sibling_scope_validation(),
            case_margin_vs_padding(),
            case_negative_margin_overlay(),
        ],
    }
    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-relativelayout-lab/explore-tutorial-relativelayout.py

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

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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