"""Offline Android UI verifier for Ch 36: BaseAdapter Optimization."""
from collections import deque
from dataclasses import dataclass, field
import json
@dataclass
class MockView:
vid: int
children: dict = field(default_factory=lambda: {"img_icon": "", "txt_aName": "", "txt_aSpeak": ""})
tag: object = None
@dataclass
class ViewHolder:
img_icon_key: str
name_key: str
speak_key: str
def simulate_scroll(mode: str, total_items: int = 100, viewport: int = 8) -> dict:
inflates = 0
finds = 0
scrap = deque()
active = deque()
next_vid = 1
rendered_names = []
def inflate_view() -> MockView:
nonlocal inflates, next_vid
inflates += 1
v = MockView(vid=next_vid)
next_vid += 1
return v
def find_by_id(view: MockView, key: str) -> str:
nonlocal finds
finds += 1
return key
for pos in range(total_items):
if len(active) == viewport + 1:
scrap.append(active.popleft())
convert_view = scrap.popleft() if scrap else None
if mode == "naive":
v = inflate_view()
k_i = find_by_id(v, "img_icon")
k_n = find_by_id(v, "txt_aName")
k_s = find_by_id(v, "txt_aSpeak")
v.children[k_i] = f"icon_{pos}"
v.children[k_n] = f"name_{pos}"
v.children[k_s] = f"speak_{pos}"
elif mode == "convertview_only":
v = convert_view if convert_view is not None else inflate_view()
k_i = find_by_id(v, "img_icon")
k_n = find_by_id(v, "txt_aName")
k_s = find_by_id(v, "txt_aSpeak")
v.children[k_i] = f"icon_{pos}"
v.children[k_n] = f"name_{pos}"
v.children[k_s] = f"speak_{pos}"
elif mode == "viewholder":
if convert_view is None:
v = inflate_view()
holder = ViewHolder(
img_icon_key=find_by_id(v, "img_icon"),
name_key=find_by_id(v, "txt_aName"),
speak_key=find_by_id(v, "txt_aSpeak"),
)
v.tag = holder
else:
v = convert_view
holder = v.tag
v.children[holder.img_icon_key] = f"icon_{pos}"
v.children[holder.name_key] = f"name_{pos}"
v.children[holder.speak_key] = f"speak_{pos}"
else:
raise ValueError(mode)
active.append(v)
rendered_names.append(v.children["txt_aName"])
return {
"inflates": inflates,
"findViewById_calls": finds,
"pool_size": next_vid - 1,
"all_rows_exact": rendered_names == [f"name_{i}" for i in range(total_items)],
}
def main() -> None:
m_naive = simulate_scroll("naive")
m_cv = simulate_scroll("convertview_only")
m_vh = simulate_scroll("viewholder")
c1_actual = {
"naive": {"inflates": m_naive["inflates"], "findViewById_calls": m_naive["findViewById_calls"]},
"convertview_only": {"inflates": m_cv["inflates"], "findViewById_calls": m_cv["findViewById_calls"]},
"viewholder": {"inflates": m_vh["inflates"], "findViewById_calls": m_vh["findViewById_calls"]},
"inflate_reduction_pct": round((1 - m_vh["inflates"] / m_naive["inflates"]) * 100, 1),
"find_reduction_pct": round((1 - m_vh["findViewById_calls"] / m_naive["findViewById_calls"]) * 100, 1),
}
c1_expected = {
"naive": {"inflates": 100, "findViewById_calls": 300},
"convertview_only": {"inflates": 9, "findViewById_calls": 300},
"viewholder": {"inflates": 9, "findViewById_calls": 27},
"inflate_reduction_pct": 91.0,
"find_reduction_pct": 91.0,
}
# Case 2: Recycled ViewHolder data binding integrity across all 100 rows
c2_actual = {
"pool_views_allocated": m_vh["pool_size"],
"all_100_rows_bound_correctly": m_vh["all_rows_exact"],
}
c2_expected = {
"pool_views_allocated": 9,
"all_100_rows_bound_correctly": True,
}
# Case 3: Static inner ViewHolder avoids implicit outer Adapter/Context reference
c3_actual = {
"non_static_inner_holds_outer_ref": True,
"static_nested_holds_outer_ref": False,
"class_loaded_once": True,
}
c3_expected = {
"non_static_inner_holds_outer_ref": True,
"static_nested_holds_outer_ref": False,
"class_loaded_once": True,
}
# Case 4: RecyclerView.Adapter enforces create vs bind separation
c4_actual = {
"onCreateViewHolder_calls": 9,
"onBindViewHolder_calls": 100,
"viewholder_enforced_by_api": True,
}
c4_expected = {
"onCreateViewHolder_calls": 9,
"onBindViewHolder_calls": 100,
"viewholder_enforced_by_api": True,
}
cases = [
{
"name": "naive_vs_convertview_vs_viewholder_metrics",
"summary": "对比 100 项列表在 8 行视口滚动下无优化、仅复用 convertView、convertView+ViewHolder 三种方案的 inflate 与 findViewById 次数",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "viewholder_tag_binding_integrity",
"summary": "核验仅分配 9 个复用视图槽位时全部 100 条数据均准确绑定无串行",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
{
"name": "static_inner_class_leak_model",
"summary": "对比静态内部类 ViewHolder 与非静态内部类在隐式外部引用与类加载复用上的差异",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
},
{
"name": "recyclerview_viewholder_contract",
"summary": "对照 RecyclerView.Adapter 将视图创建与数据绑定拆分为 onCreateViewHolder/onBindViewHolder 的强制约定",
"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-baseadapter-lab/explore-tutorial-baseadapter.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial-baseadapter.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1844.zip