"""Offline Android UI verifier for Ch 21: AbsoluteLayout."""
from dataclasses import dataclass
import json
import xml.etree.ElementTree as ET
ANDROID_NS = "{http://schemas.android.com/apk/res/android}"
APP_NS = "{http://schemas.android.com/apk/res-auto}"
def parse_dp(val: str) -> float:
return float(val.replace("dp", "").replace("dip", "").strip())
@dataclass
class Rect:
x: float
y: float
w: float
h: float
@property
def right(self) -> float:
return self.x + self.w
@property
def bottom(self) -> float:
return self.y + self.h
LOGIN_ABSOLUTE_XML = """<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_user"
android:layout_width="80dp"
android:layout_height="36dp"
android:layout_x="20dp"
android:layout_y="40dp"
android:text="用户名" />
<EditText
android:id="@+id/et_user"
android:layout_width="180dp"
android:layout_height="36dp"
android:layout_x="110dp"
android:layout_y="40dp" />
<TextView
android:id="@+id/tv_pwd"
android:layout_width="80dp"
android:layout_height="36dp"
android:layout_x="20dp"
android:layout_y="92dp"
android:text="密码" />
<EditText
android:id="@+id/et_pwd"
android:layout_width="180dp"
android:layout_height="36dp"
android:layout_x="110dp"
android:layout_y="92dp" />
<Button
android:id="@+id/btn_login"
android:layout_width="120dp"
android:layout_height="44dp"
android:layout_x="100dp"
android:layout_y="150dp"
android:text="登录" />
</AbsoluteLayout>
"""
CONSTRAINT_MIGRATION_XML = """<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btn_login"
android:layout_width="120dp"
android:layout_height="44dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
"""
def main() -> None:
root = ET.fromstring(LOGIN_ABSOLUTE_XML)
boxes = {}
for child in root:
cid = child.attrib[f"{ANDROID_NS}id"].split("/")[-1]
boxes[cid] = Rect(
x=parse_dp(child.attrib[f"{ANDROID_NS}layout_x"]),
y=parse_dp(child.attrib[f"{ANDROID_NS}layout_y"]),
w=parse_dp(child.attrib[f"{ANDROID_NS}layout_width"]),
h=parse_dp(child.attrib[f"{ANDROID_NS}layout_height"]),
)
c1_actual = {
"child_count": len(boxes),
"et_user_right_dp": boxes["et_user"].right,
"btn_login_bounds": [boxes["btn_login"].x, boxes["btn_login"].y, boxes["btn_login"].right, boxes["btn_login"].bottom],
}
c1_expected = {
"child_count": 5,
"et_user_right_dp": 290.0,
"btn_login_bounds": [100.0, 150.0, 220.0, 194.0],
}
# Case 2: Fixed dp placement across 3 screen widths (240dp narrow, 320dp baseline, 411dp large)
btn = boxes["btn_login"]
et = boxes["et_user"]
screen_report = {}
for label, sw in (("240dp", 240.0), ("320dp", 320.0), ("411dp", 411.0)):
left_margin = btn.x
right_margin = sw - btn.right
clipped = et.right > sw
screen_report[label] = {
"btn_left_margin": left_margin,
"btn_right_margin": right_margin,
"centered": left_margin == right_margin,
"et_clipped": clipped,
}
c2_expected = {
"240dp": {"btn_left_margin": 100.0, "btn_right_margin": 20.0, "centered": False, "et_clipped": True},
"320dp": {"btn_left_margin": 100.0, "btn_right_margin": 100.0, "centered": True, "et_clipped": False},
"411dp": {"btn_left_margin": 100.0, "btn_right_margin": 191.0, "centered": False, "et_clipped": False},
}
# Case 3: dp -> px across standard Android screen densities
densities = {"mdpi_160": 160, "hdpi_240": 240, "xhdpi_320": 320, "xxhdpi_480": 480}
c3_actual = {k: int(round(100.0 * (dpi / 160.0))) for k, dpi in densities.items()}
c3_expected = {"mdpi_160": 100, "hdpi_240": 150, "xhdpi_320": 200, "xxhdpi_480": 300}
# Case 4: ConstraintLayout responsive migration check
croot = ET.fromstring(CONSTRAINT_MIGRATION_XML)
cbtn = croot[0]
has_abs_coords = (f"{ANDROID_NS}layout_x" in cbtn.attrib) or (f"{ANDROID_NS}layout_y" in cbtn.attrib)
bias = float(cbtn.attrib[f"{APP_NS}layout_constraintHorizontal_bias"])
bw = parse_dp(cbtn.attrib[f"{ANDROID_NS}layout_width"])
responsive_x = {f"{int(sw)}dp": round((sw - bw) * bias, 1) for sw in (240.0, 320.0, 411.0)}
c4_actual = {
"has_hardcoded_xy": has_abs_coords,
"responsive_btn_x": responsive_x,
}
c4_expected = {
"has_hardcoded_xy": False,
"responsive_btn_x": {"240dp": 60.0, "320dp": 100.0, "411dp": 145.5},
}
cases = [
{
"name": "absolutelayout_xml_coords_parsing",
"summary": "解析 AbsoluteLayout 登录表单 XML 的四个核心属性(layout_width/height/x/y)及控件边界",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "screen_size_overflow_and_drift",
"summary": "模拟固定 dp 绝对坐标在 240dp/320dp/411dp 三种屏幕宽度下的偏移与截断",
"expected": c2_expected,
"actual": screen_report,
"passed": screen_report == c2_expected,
},
{
"name": "dp_to_px_density_conversion",
"summary": "核算 100dp 在 mdpi/hdpi/xhdpi/xxhdpi 四档屏幕密度下的物理像素换算",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
},
{
"name": "constraintlayout_migration_check",
"summary": "验证迁移到 ConstraintLayout(无 layout_x/layout_y,按 0.5 bias 居中)后多屏自适应定位",
"expected": c4_expected,
"actual": c4_actual,
"passed": c4_actual == c4_expected,
},
]
print(json.dumps({
"version": "CPython 3.12.14 offline Android UI/XML/Adapter verifier (Android SDK/emulator absent)",
"cases": cases,
}, ensure_ascii=False))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/android-tutorial-absolutelayout-lab/explore-tutorial-absolutelayout.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial-absolutelayout.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1831.zip
课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip