"""Offline Android UI verifier for Ch 22: TextView."""
import json
import re
import xml.etree.ElementTree as ET
ANDROID_NS = "{http://schemas.android.com/apk/res/android}"
BASIC_TEXTVIEW_XML = """<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:id="@+id/txtOne"
android:layout_width="200dp"
android:layout_height="200dp"
android:gravity="center"
android:text="TextView(显示框)"
android:textColor="#EA5246"
android:textStyle="bold|italic"
android:textSize="18sp"
android:shadowColor="#F9F900"
android:shadowDx="10.0"
android:shadowDy="10.0"
android:shadowRadius="3.0" />
<TextView
android:id="@+id/txtMarquee"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:focusable="true"
android:focusableInTouchMode="true" />
</RelativeLayout>
"""
SHAPE_BORDER_XML = """<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#87CEEB" />
<stroke android:width="2px" android:color="#000000" />
<corners android:topLeftRadius="10px" android:topRightRadius="10px"
android:bottomLeftRadius="10px" android:bottomRightRadius="10px" />
<gradient android:angle="270" android:startColor="#FCD209" android:endColor="#C0C0C0" />
<padding android:left="5dp" android:top="5dp" android:right="5dp" android:bottom="5dp" />
</shape>
"""
def main() -> None:
root = ET.fromstring(BASIC_TEXTVIEW_XML)
tv1, tv_m = root[0], root[1]
shape = ET.fromstring(SHAPE_BORDER_XML)
# Unit conversion at 320dpi (2.0x density), fontScale=1.25
density, font_scale = 2.0, 1.25
c1_actual = {
"styles": tv1.attrib[f"{ANDROID_NS}textStyle"].split("|"),
"shadow_enabled": float(tv1.attrib[f"{ANDROID_NS}shadowRadius"]) > 0,
"marquee_ready": all([
tv_m.attrib[f"{ANDROID_NS}singleLine"] == "true",
tv_m.attrib[f"{ANDROID_NS}ellipsize"] == "marquee",
tv_m.attrib[f"{ANDROID_NS}marqueeRepeatLimit"] == "marquee_forever",
tv_m.attrib[f"{ANDROID_NS}focusable"] == "true",
tv_m.attrib[f"{ANDROID_NS}focusableInTouchMode"] == "true",
]),
"shape_tags": [child.tag for child in shape],
"gradient_angle_mod45_valid": int(shape.find("gradient").attrib[f"{ANDROID_NS}angle"]) % 45 == 0,
"units_px": {
"200dp": int(200 * density),
"18sp_1.25x": int(18 * density * font_scale),
"72pt_at_320dpi": int(72 * (320 / 72.0)),
},
}
c1_expected = {
"styles": ["bold", "italic"],
"shadow_enabled": True,
"marquee_ready": True,
"shape_tags": ["solid", "stroke", "corners", "gradient", "padding"],
"gradient_angle_mod45_valid": True,
"units_px": {"200dp": 400, "18sp_1.25x": 45, "72pt_at_320dpi": 320},
}
# Case 2: Compound drawables [left, top, right, bottom] & autoLink detection
drawables = ["left_icon", "top_icon", "right_icon", "bottom_icon"]
top_bounds = (100, 0, 200, 200)
sample_text = "访问 https://example.org 或联系 dev@example.org 致电 13800138000"
links_found = {
"web": re.findall(r"https?://[^\s]+", sample_text),
"email": re.findall(r"[\w.+-]+@[\w.-]+\.[a-zA-Z]{2,}", sample_text),
"phone": re.findall(r"\b1\d{10}\b", sample_text),
}
c2_actual = {
"top_drawable_index": 1,
"top_drawable_name": drawables[1],
"top_bounds_wh_px": [top_bounds[2] - top_bounds[0], top_bounds[3] - top_bounds[1]],
"autolink_matches": links_found,
}
c2_expected = {
"top_drawable_index": 1,
"top_drawable_name": "top_icon",
"top_bounds_wh_px": [100, 200],
"autolink_matches": {
"web": ["https://example.org"],
"email": ["dev@example.org"],
"phone": ["13800138000"],
},
}
# Case 3: Html subset & SpannableString ranges
html_snippet = "<font color='blue'><b>标题</b></font><a href='https://example.org'>链接</a><img src='icon'/>"
html_tags = re.findall(r"<([a-zA-Z]+)\b", html_snippet)
span_text = "红色打电话斜体删除线绿色下划线图片:."
span_specs = [
("ForegroundColorSpan(RED)", 0, 2),
("URLSpan(tel)", 2, 5),
("StyleSpan(BOLD_ITALIC)", 5, 7),
("StrikethroughSpan", 7, 10),
("UnderlineSpan", 10, 16),
("ForegroundColorSpan(GREEN)", 10, 13),
("ImageSpan", 18, 19),
]
c3_actual = {
"html_tags": html_tags,
"span_slices": {name: span_text[s:e] for name, s, e in span_specs},
}
c3_expected = {
"html_tags": ["font", "b", "a", "img"],
"span_slices": {
"ForegroundColorSpan(RED)": "红色",
"URLSpan(tel)": "打电话",
"StyleSpan(BOLD_ITALIC)": "斜体",
"StrikethroughSpan": "删除线",
"UnderlineSpan": "绿色下划线图",
"ForegroundColorSpan(GREEN)": "绿色下",
"ImageSpan": ".",
},
}
# Case 4: ClickableSpan indexOf prefix-collision bug vs cumulative offset fix & lineSpacing
names = [f"好友{i}" for i in range(20)]
joined = ",".join(names)
prefix_len = 2 # "p."
naive_starts = [joined.index(n) + prefix_len for n in names]
# Note "好友1" matches inside "好友1" (index 4), while "好友10" is distinct; test reverse order ["好友10", "好友1"]!
order_names = ["好友10", "好友1"]
order_joined = ",".join(order_names)
naive_collide = [order_joined.index(n) for n in order_names] # both find 0!
cursor = 0
safe_spans = []
for n in order_names:
safe_spans.append((cursor, cursor + len(n)))
cursor += len(n) + 1
base_line_h = 20.0
line_height_result = base_line_h * 1.2 + 3.0
c4_actual = {
"twenty_friends_count": len(naive_starts),
"naive_indexof_collision_on_prefix": naive_collide,
"safe_cursor_spans": safe_spans,
"line_spacing_result_dp": round(line_height_result, 1),
}
c4_expected = {
"twenty_friends_count": 20,
"naive_indexof_collision_on_prefix": [0, 0],
"safe_cursor_spans": [(0, 4), (5, 8)],
"line_spacing_result_dp": 27.0,
}
cases = [
{
"name": "textview_xml_units_and_shadow",
"summary": "解析 TextView 基础属性、阴影、跑马灯、shape 边框 XML 及 dp/sp/pt 换算",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "compound_drawables_bounds_and_autolink",
"summary": "验证 CompoundDrawables 左上右下四位数组索引、setBounds 尺寸与 autoLink 正则识别",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
{
"name": "html_subset_and_spannable_ranges",
"summary": "核对 TextView 支持的 HTML 子集标签与 SpannableString 7 组区间切片对应",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
},
{
"name": "clickable_span_prefix_collision_fix",
"summary": "对比 ClickableSpan 使用 indexOf 产生前缀重叠冲突与游标累进定位修复,并验证行间距公式",
"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-textview-lab/explore-tutorial-textview.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial-textview.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1958.zip