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

运行 LinearLayout 权重(0dp/wrap_content/fill_parent 反比)、分割线与 layout_gravity 交叉轴离线求解器

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

import json
import xml.etree.ElementTree as ET
from fractions import Fraction

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


def distribute_linear_weights(parent_size: int, base_sizes: list[int], weights: list[int]) -> list[Fraction]:
    remaining = Fraction(parent_size - sum(base_sizes))
    total_w = Fraction(sum(weights))
    return [Fraction(b) + remaining * (Fraction(w) / total_w) for b, w in zip(base_sizes, weights)]


def case_weight_zero_dp_and_wrap() -> dict:
    xml_zero = """<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal">
        <LinearLayout android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1"/>
        <LinearLayout android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="2"/>
    </LinearLayout>"""
    xml_wrap = """<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal">
        <TextView android:layout_weight="1" android:layout_width="wrap_content" android:layout_height="fill_parent" android:text="one"/>
        <TextView android:layout_weight="2" android:layout_width="wrap_content" android:layout_height="fill_parent" android:text="two"/>
        <TextView android:layout_weight="3" android:layout_width="wrap_content" android:layout_height="fill_parent" android:text="three"/>
    </LinearLayout>"""
    r_zero = ET.fromstring(xml_zero)
    w_zero = [int(c.attrib[f"{ANDROID_NS}layout_weight"]) for c in r_zero]
    res_1_2 = [int(x) for x in distribute_linear_weights(300, [0, 0], w_zero)]
    res_1_1 = [int(x) for x in distribute_linear_weights(300, [0, 0], [1, 1])]

    r_wrap = ET.fromstring(xml_wrap)
    w_wrap = [int(c.attrib[f"{ANDROID_NS}layout_weight"]) for c in r_wrap]
    # Intrinsic widths: "one"=30dp, "two"=30dp, "three"=48dp; remaining = 300 - 108 = 192dp
    res_wrap = [int(x) for x in distribute_linear_weights(300, [30, 30, 48], w_wrap)]
    java_lp = "setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1));"
    actual = {
        "zero_dp_1_2_on_300": res_1_2,
        "zero_dp_1_1_on_300": res_1_1,
        "wrap_content_1_2_3_on_300": res_wrap,
        "java_layoutparams_weight_arg": 1 if ", 1))" in java_lp else 0,
    }
    expected = {
        "zero_dp_1_2_on_300": [100, 200],
        "zero_dp_1_1_on_300": [150, 150],
        "wrap_content_1_2_3_on_300": [62, 94, 144],
        "java_layoutparams_weight_arg": 1,
    }
    return {
        "name": "linearlayout_weight_zero_dp_and_wrap_content",
        "summary": "解析 0dp 与 wrap_content 下 LinearLayout 权重分配公式及 Java LayoutParams 权重构造",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_weight_match_parent_inversion() -> dict:
    xml_fill = """<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent" android:layout_height="match_parent">
        <TextView android:layout_weight="1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="one"/>
        <TextView android:layout_weight="2" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="two"/>
        <TextView android:layout_weight="3" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="three"/>
    </LinearLayout>"""
    root = ET.fromstring(xml_fill)
    w_123 = [int(c.attrib[f"{ANDROID_NS}layout_weight"]) for c in root]
    # Parent width normalized to 1 unit; each fill_parent child starts at 1 unit
    r_123 = [str(f) for f in distribute_linear_weights(1, [1, 1, 1], w_123)]
    r_111 = [str(f) for f in distribute_linear_weights(1, [1, 1, 1], [1, 1, 1])]
    r_234 = [str(f) for f in distribute_linear_weights(1, [1, 1, 1], [2, 3, 4])]
    actual = {
        "fill_parent_1_2_3": r_123,
        "fill_parent_1_1_1": r_111,
        "fill_parent_2_3_4": r_234,
        "three_collapses_to_zero": r_123[2] == "0",
    }
    expected = {
        "fill_parent_1_2_3": ["2/3", "1/3", "0"],
        "fill_parent_1_1_1": ["1/3", "1/3", "1/3"],
        "fill_parent_2_3_4": ["5/9", "1/3", "1/9"],
        "three_collapses_to_zero": True,
    }
    return {
        "name": "linearlayout_weight_match_parent_inversion",
        "summary": "验证 fill_parent/match_parent 下权重反比公式(1:2:3->2/3:1/3:0、1:1:1、2:3:4->5/9:1/3:1/9)",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_divider_and_form() -> dict:
    view_line = '<View xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="1px" android:background="#000000" />'
    div_xml = """<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent" android:layout_height="match_parent"
        android:divider="@drawable/ktv_line_div" android:orientation="vertical"
        android:showDividers="middle" android:dividerPadding="10dp">
        <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="按钮1" />
        <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="按钮2" />
        <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="按钮3" />
    </LinearLayout>"""
    form_xml = """<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:layout_width="wrap_content" android:layout_height="wrap_content" android:text="请输入要保存的电话号码"/>
        <EditText android:layout_width="fill_parent" android:layout_height="wrap_content"/>
        <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="right">
            <Button 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>
    </LinearLayout>"""
    v_el = ET.fromstring(view_line)
    d_root = ET.fromstring(div_xml)
    f_root = ET.fromstring(form_xml)
    btn_count = len(list(d_root))
    show = d_root.attrib[f"{ANDROID_NS}showDividers"]
    middle_dividers = max(0, btn_count - 1) if show == "middle" else 0
    inner_bar = f_root.find("LinearLayout")
    assert inner_bar is not None
    actual = {
        "view_divider_height": v_el.attrib[f"{ANDROID_NS}layout_height"],
        "middle_divider_slots": middle_dividers,
        "divider_padding": d_root.attrib[f"{ANDROID_NS}dividerPadding"],
        "nested_button_bar_gravity": inner_bar.attrib[f"{ANDROID_NS}gravity"],
        "nested_buttons": [b.attrib[f"{ANDROID_NS}text"] for b in inner_bar],
    }
    expected = {
        "view_divider_height": "1px",
        "middle_divider_slots": 2,
        "divider_padding": "10dp",
        "nested_button_bar_gravity": "right",
        "nested_buttons": ["保存", "清空"],
    }
    return {
        "name": "linearlayout_divider_and_form_layout",
        "summary": "解析 1px View 分割线、android:divider/showDividers=middle 槽位数及嵌套表单右对齐按钮栏",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_gravity_axis_constraint() -> dict:
    def effective_layout_gravity(orientation: str, flags: list[str]) -> list[str]:
        if orientation == "vertical":
            allowed = {"left", "right", "start", "end", "center_horizontal"}
        else:
            allowed = {"top", "bottom", "center_vertical"}
        return [f for f in flags if f in allowed]

    xml_horiz = """<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:gravity="left">
        <TextView android:layout_width="wrap_content" android:layout_height="200dp" android:layout_gravity="left" android:gravity="center" android:text="A" />
        <TextView android:layout_width="wrap_content" android:layout_height="200dp" android:layout_gravity="right" android:gravity="center" android:text="B" />
    </LinearLayout>"""
    root = ET.fromstring(xml_horiz)
    orient = root.attrib[f"{ANDROID_NS}orientation"]
    child_lgs = [c.attrib[f"{ANDROID_NS}layout_gravity"] for c in root]
    actual = {
        "horizontal_child_effective_lgs": [effective_layout_gravity(orient, [lg]) for lg in child_lgs],
        "horizontal_allows_bottom": effective_layout_gravity("horizontal", ["right", "bottom"]),
        "vertical_allows_right": effective_layout_gravity("vertical", ["right", "bottom"]),
    }
    expected = {
        "horizontal_child_effective_lgs": [[], []],
        "horizontal_allows_bottom": ["bottom"],
        "vertical_allows_right": ["right"],
    }
    return {
        "name": "linearlayout_gravity_axis_constraint",
        "summary": "验证 LinearLayout 中 layout_gravity 仅在交叉轴生效(horizontal 忽略 left/right,vertical 忽略 top/bottom)",
        "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_weight_zero_dp_and_wrap(),
            case_weight_match_parent_inversion(),
            case_divider_and_form(),
            case_gravity_axis_constraint(),
        ],
    }
    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-linearlayout-lab/explore-tutorial-linearlayout.py

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

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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