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

运行离线 ListView setEmptyView、动态增删插清 CRUD、可见行局部刷新与 DiffUtil 对照核验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-listview-update.py
explore-tutorial-listview-update.py163 行
"""Offline Android UI verifier for Ch 39: ListView Data Updates."""
from dataclasses import dataclass
import json


@dataclass
class DataItem:
    img_id: int
    content: str


class DynamicAdapter:
    def __init__(self, items: list | None = None):
        self.data = list(items) if items is not None else []
        self.notify_calls = 0

    def get_count(self) -> int:
        return len(self.data)

    def add(self, item: DataItem, position: int | None = None) -> None:
        if position is None:
            self.data.append(item)
        else:
            self.data.insert(position, item)
        self.notify_calls += 1

    def remove_obj(self, item: DataItem) -> None:
        if item in self.data:
            self.data.remove(item)
        self.notify_calls += 1

    def remove_at(self, position: int) -> None:
        if 0 <= position < len(self.data):
            self.data.pop(position)
        self.notify_calls += 1

    def clear(self) -> None:
        self.data.clear()
        self.notify_calls += 1


def empty_view_state(count: int) -> dict:
    return {
        "emptyView_visibility": "VISIBLE" if count == 0 else "GONE",
        "listView_visibility": "GONE" if count == 0 else "VISIBLE",
    }


def partial_update(visible_rows: dict, first_visible: int, target_pos: int, new_text: str) -> dict:
    child_idx = target_pos - first_visible
    if 0 <= child_idx < len(visible_rows):
        visible_rows[child_idx] = new_text
        return {"updated": True, "child_index": child_idx, "text": visible_rows[child_idx]}
    return {"updated": False, "child_index": child_idx, "text": None}


def main() -> None:
    # Case 1: setEmptyView automatic visibility toggle
    adapter = DynamicAdapter()
    state_empty = empty_view_state(adapter.get_count())
    adapter.add(DataItem(1, "记录 x 1"))
    state_non_empty = empty_view_state(adapter.get_count())
    c1_actual = {"when_empty": state_empty, "after_first_add": state_non_empty}
    c1_expected = {
        "when_empty": {"emptyView_visibility": "VISIBLE", "listView_visibility": "GONE"},
        "after_first_add": {"emptyView_visibility": "GONE", "listView_visibility": "VISIBLE"},
    }

    # Case 2: CRUD mutations (append, insert at index 4, remove obj, remove index 2, clear)
    ad = DynamicAdapter()
    items = [DataItem(1, f"条目-{i}") for i in range(1, 9)]
    for it in items:
        ad.add(it)
    item5 = items[4]  # 条目-5
    ad.add(DataItem(1, "条目-9"), position=4)  # insert at 5th slot (0-based 4)
    after_insert = [d.content for d in ad.data]
    ad.remove_obj(item5)
    after_remove_obj = [d.content for d in ad.data]
    ad.remove_at(2)  # removes 3rd item (条目-3)
    after_remove_pos = [d.content for d in ad.data]
    ad.clear()
    c2_actual = {
        "after_insert_pos4": after_insert,
        "after_remove_obj5": after_remove_obj,
        "after_remove_pos2": after_remove_pos,
        "after_clear_count": ad.get_count(),
        "notify_count": ad.notify_calls,
    }
    c2_expected = {
        "after_insert_pos4": ["条目-1", "条目-2", "条目-3", "条目-4", "条目-9", "条目-5", "条目-6", "条目-7", "条目-8"],
        "after_remove_obj5": ["条目-1", "条目-2", "条目-3", "条目-4", "条目-9", "条目-6", "条目-7", "条目-8"],
        "after_remove_pos2": ["条目-1", "条目-2", "条目-4", "条目-9", "条目-6", "条目-7", "条目-8"],
        "after_clear_count": 0,
        "notify_count": 12,
    }

    # Case 3: Partial visible-row update via firstVisiblePosition & bounds guard
    visible = {0: "条目-10", 1: "条目-11", 2: "条目-12", 3: "条目-13"}
    on_screen = partial_update(visible, first_visible=10, target_pos=12, new_text="条目-12(已更新)")
    off_screen = partial_update(visible, first_visible=10, target_pos=25, new_text="条目-25(已更新)")
    c3_actual = {"on_screen_pos12": on_screen, "off_screen_pos25": off_screen}
    c3_expected = {
        "on_screen_pos12": {"updated": True, "child_index": 2, "text": "条目-12(已更新)"},
        "off_screen_pos25": {"updated": False, "child_index": 15, "text": None},
    }

    # Case 4: BaseAdapter.notifyDataSetChanged vs DiffUtil single-item change op count
    old_list = [(i, f"row-{i}") for i in range(50)]
    new_list = list(old_list)
    new_list[17] = (17, "row-17-edited")
    diff_changed_indices = [i for i, (a, b) in enumerate(zip(old_list, new_list)) if a != b]
    c4_actual = {
        "list_size": len(old_list),
        "notifyDataSetChanged_rebinds_viewport": 10,
        "diffutil_changed_indices": diff_changed_indices,
        "diffutil_minimal_ops": len(diff_changed_indices),
    }
    c4_expected = {
        "list_size": 50,
        "notifyDataSetChanged_rebinds_viewport": 10,
        "diffutil_changed_indices": [17],
        "diffutil_minimal_ops": 1,
    }

    cases = [
        {
            "name": "empty_view_visibility_sync",
            "summary": "验证 ListView.setEmptyView 在数据集空与非空状态下的自动显隐切换",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "crud_mutations_and_notify_count",
            "summary": "模拟尾插、指定位置插入(index=4)、按对象删除、按索引删除(index=2)与 clear 清空及 notifyDataSetChanged 次数",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
        {
            "name": "partial_visible_row_update_bounds",
            "summary": "验证基于 getFirstVisiblePosition() 的局部单行刷新偏移换算与离屏越界保护",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        },
        {
            "name": "notify_vs_diffutil_minimal_ops",
            "summary": "对比 notifyDataSetChanged 视口整批重绑与现代 RecyclerView DiffUtil 单项增量更新差异",
            "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-update-lab/explore-tutorial-listview-update.py

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

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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