"""Offline Android UI verifier for Ch 35: ListView Basics."""
from dataclasses import dataclass
import json
import xml.etree.ElementTree as ET
ANDROID_NS = "{http://schemas.android.com/apk/res/android}"
LISTVIEW_XML = """<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/list_animal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#CCCCCC"
android:dividerHeight="1dp"
android:headerDividersEnabled="true"
android:footerDividersEnabled="true"
android:stackFromBottom="true"
android:cacheColorHint="#00000000"
android:scrollbars="none" />
"""
@dataclass
class Animal:
name: str
speak: str
icon: str
class ListViewModel:
def __init__(self, api_level: int = 18):
self.api_level = api_level
self.headers = []
self.footers = []
self.adapter_data = None
def add_header(self, label: str, selectable: bool = True) -> dict:
if self.adapter_data is not None and self.api_level < 19:
return {"ok": False, "error": "IllegalStateException: Cannot add header view to list -- setAdapter has already been called"}
self.headers.append({"label": label, "selectable": selectable})
return {"ok": True}
def add_footer(self, label: str, selectable: bool = True) -> None:
self.footers.append({"label": label, "selectable": selectable})
def set_adapter(self, data: list) -> None:
self.adapter_data = data
def total_count(self) -> int:
return len(self.headers) + len(self.adapter_data or []) + len(self.footers)
def click(self, position: int) -> dict:
h = len(self.headers)
n = len(self.adapter_data or [])
if position < h:
return {"position": position, "zone": "header", "delivered": self.headers[position]["selectable"]}
if position < h + n:
data_idx = position - h
return {"position": position, "zone": "data", "data_index": data_idx, "item": self.adapter_data[data_idx].name, "delivered": True}
f_idx = position - h - n
return {"position": position, "zone": "footer", "delivered": self.footers[f_idx]["selectable"]}
def main() -> None:
animals = [
Animal("狗说", "旺旺", "ic_icon_dog"),
Animal("牛说", "哞哞", "ic_icon_cow"),
Animal("鸭说", "嘎嘎", "ic_icon_duck"),
Animal("鱼说", "吐泡泡", "ic_icon_fish"),
Animal("马说", "嘶鸣", "ic_icon_horse"),
]
c1_actual = {
"count": len(animals),
"item_ids": list(range(len(animals))),
"first_bound": {"name": animals[0].name, "speak": animals[0].speak, "icon": animals[0].icon},
}
c1_expected = {
"count": 5,
"item_ids": [0, 1, 2, 3, 4],
"first_bound": {"name": "狗说", "speak": "旺旺", "icon": "ic_icon_dog"},
}
# Case 2: Header/Footer order guard (API < 19) & position offset shift
lv_bad = ListViewModel(api_level=18)
lv_bad.set_adapter(animals)
late_header_res = lv_bad.add_header("表头")
lv = ListViewModel(api_level=18)
lv.add_header("表头", selectable=False)
lv.add_footer("表尾", selectable=False)
lv.set_adapter(animals)
c2_actual = {
"late_header_on_api18": late_header_res,
"total_items_with_hf": lv.total_count(),
"click_pos0_header": lv.click(0),
"click_pos1_first_data": lv.click(1),
"click_pos6_footer": lv.click(6),
}
c2_expected = {
"late_header_on_api18": {
"ok": False,
"error": "IllegalStateException: Cannot add header view to list -- setAdapter has already been called",
},
"total_items_with_hf": 7,
"click_pos0_header": {"position": 0, "zone": "header", "delivered": False},
"click_pos1_first_data": {"position": 1, "zone": "data", "data_index": 0, "item": "狗说", "delivered": True},
"click_pos6_footer": {"position": 6, "zone": "footer", "delivered": False},
}
# Case 3: Divider, stackFromBottom, cacheColorHint XML attributes
node = ET.fromstring(LISTVIEW_XML)
c3_actual = {
"divider": node.attrib[f"{ANDROID_NS}divider"],
"dividerHeight": node.attrib[f"{ANDROID_NS}dividerHeight"],
"headerDividersEnabled": node.attrib[f"{ANDROID_NS}headerDividersEnabled"] == "true",
"footerDividersEnabled": node.attrib[f"{ANDROID_NS}footerDividersEnabled"] == "true",
"stackFromBottom": node.attrib[f"{ANDROID_NS}stackFromBottom"] == "true",
"cacheColorHint": node.attrib[f"{ANDROID_NS}cacheColorHint"],
"scrollbars": node.attrib[f"{ANDROID_NS}scrollbars"],
}
c3_expected = {
"divider": "#CCCCCC",
"dividerHeight": "1dp",
"headerDividersEnabled": True,
"footerDividersEnabled": True,
"stackFromBottom": True,
"cacheColorHint": "#00000000",
"scrollbars": "none",
}
# Case 4: Scrollbar hide API correction (false hides, true shows) & stackFromBottom initial slice
viewport_rows = 3
normal_visible = [a.name for a in animals[:viewport_rows]]
stack_bottom_visible = [a.name for a in animals[-viewport_rows:]]
c4_actual = {
"hide_scrollbar_flag": False,
"normal_initial_visible": normal_visible,
"stack_from_bottom_visible": stack_bottom_visible,
}
c4_expected = {
"hide_scrollbar_flag": False,
"normal_initial_visible": ["狗说", "牛说", "鸭说"],
"stack_from_bottom_visible": ["鸭说", "鱼说", "马说"],
}
cases = [
{
"name": "animal_baseadapter_binding",
"summary": "模拟 Animal 实体与自定义 BaseAdapter(getCount/getItemId/getView)数据绑定",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "header_footer_position_offset_and_order",
"summary": "验证 API<19 表头须先于 setAdapter 添加、表头偏移导致首条数据 position=1 及不可选表头拦截",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
{
"name": "divider_and_visual_attrs",
"summary": "解析 ListView 分隔线、stackFromBottom、透明 cacheColorHint 与隐藏滚动条属性",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
},
{
"name": "scrollbar_disable_api_correction",
"summary": "验证隐藏垂直滚动条须传 setVerticalScrollBarEnabled(false) 及 stackFromBottom 视口锚定末尾",
"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-listview-lab/explore-tutorial-listview.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial-listview.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1915.zip