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

运行 ExpandableListView 分组展开投影、64 位 packedPosition 与点击开关离线验证

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-expandablelistview.py
explore-tutorial-expandablelistview.py234 行
"""Offline Android verifier for Ch45: ExpandableListView group/child hierarchy & clickability."""
import json
import xml.etree.ElementTree as ET

ANDROID_NS = "{http://schemas.android.com/apk/res/android}"

PACKED_POSITION_TYPE_GROUP = 0
PACKED_POSITION_TYPE_CHILD = 1
PACKED_POSITION_MASK_CHILD = 0xFFFFFFFF
PACKED_POSITION_MASK_GROUP = 0x7FFFFFFF00000000
PACKED_POSITION_SHIFT_GROUP = 32


def pack_group(group_pos: int) -> int:
    return (group_pos & 0x7FFFFFFF) << PACKED_POSITION_SHIFT_GROUP


def pack_child(group_pos: int, child_pos: int) -> int:
    return (1 << 63) | ((group_pos & 0x7FFFFFFF) << PACKED_POSITION_SHIFT_GROUP) | (child_pos & 0xFFFFFFFF)


def unpack_position(packed: int) -> tuple[int, int, int]:
    is_child = (packed >> 63) & 1
    group_pos = (packed & PACKED_POSITION_MASK_GROUP) >> PACKED_POSITION_SHIFT_GROUP
    child_pos = (packed & PACKED_POSITION_MASK_CHILD) if is_child else -1
    return (PACKED_POSITION_TYPE_CHILD if is_child else PACKED_POSITION_TYPE_GROUP), group_pos, child_pos


class MockExpandableAdapter:
    def __init__(self, groups: list[str], children: list[list[str]], child_selectable: bool = True):
        self.groups = groups
        self.children = children
        self.child_selectable = child_selectable
        self.group_scrap: list[dict] = []
        self.child_scrap: list[dict] = []
        self.group_inflates = 0
        self.child_inflates = 0

    def get_group_count(self) -> int:
        return len(self.groups)

    def get_children_count(self, group_pos: int) -> int:
        return len(self.children[group_pos])

    def is_child_selectable(self, group_pos: int, child_pos: int) -> bool:
        return self.child_selectable

    def get_group_view(self, group_pos: int, is_expanded: bool) -> dict:
        if self.group_scrap:
            v = self.group_scrap.pop()
        else:
            self.group_inflates += 1
            v = {"holder": "ViewHolderGroup"}
        v["text"] = self.groups[group_pos]
        v["expanded"] = is_expanded
        return v

    def get_child_view(self, group_pos: int, child_pos: int) -> dict:
        if self.child_scrap:
            v = self.child_scrap.pop()
        else:
            self.child_inflates += 1
            v = {"holder": "ViewHolderItem"}
        v["text"] = self.children[group_pos][child_pos]
        v["is_last"] = child_pos == len(self.children[group_pos]) - 1
        return v


class MockExpandableListView:
    def __init__(self, adapter: MockExpandableAdapter):
        self.adapter = adapter
        self.expanded = [False] * adapter.get_group_count()

    def expand_group(self, group_pos: int) -> None:
        self.expanded[group_pos] = True

    def collapse_group(self, group_pos: int) -> None:
        self.expanded[group_pos] = False

    def visible_flat_rows(self) -> list[dict]:
        rows = []
        for g in range(self.adapter.get_group_count()):
            rows.append({"kind": "group", "g": g, "label": self.adapter.groups[g], "packed": pack_group(g)})
            if self.expanded[g]:
                for c in range(self.adapter.get_children_count(g)):
                    rows.append(
                        {"kind": "child", "g": g, "c": c, "label": self.adapter.children[g][c], "packed": pack_child(g, c)}
                    )
        return rows

    def click_child(self, group_pos: int, child_pos: int) -> str | None:
        if not self.adapter.is_child_selectable(group_pos, child_pos):
            return None
        return f"你点击了:{self.adapter.children[group_pos][child_pos]}"


def main() -> None:
    groups = ["AD", "AP", "TANK"]
    children = [
        ["剑圣", "德莱文", "男枪", "韦鲁斯"],
        ["提莫", "安妮", "天使", "泽拉斯", "狐狸"],
        ["诺手", "德邦", "奥拉夫", "龙女", "狗熊"],
    ]

    # Case 1: Group/child hierarchy, expand/collapse flat projection & packed position codec
    adapter = MockExpandableAdapter(groups, children, child_selectable=True)
    elv = MockExpandableListView(adapter)
    collapsed_len = len(elv.visible_flat_rows())
    elv.expand_group(1)  # AP (5 items)
    expanded_rows = elv.visible_flat_rows()
    packed_ap_anni = pack_child(1, 1)
    unpacked = unpack_position(packed_ap_anni)
    elv.collapse_group(1)
    act1 = {
        "group_count": adapter.get_group_count(),
        "total_children": sum(adapter.get_children_count(i) for i in range(adapter.get_group_count())),
        "collapsed_flat_count": collapsed_len,
        "expanded_ap_flat_count": len(expanded_rows),
        "unpacked_child": list(unpacked),
        "recollapsed_flat_count": len(elv.visible_flat_rows()),
    }
    exp1 = {
        "group_count": 3,
        "total_children": 14,
        "collapsed_flat_count": 3,
        "expanded_ap_flat_count": 8,
        "unpacked_child": [1, 1, 1],
        "recollapsed_flat_count": 3,
    }

    # Case 2: isChildSelectable gate controlling OnChildClickListener
    elv_blocked = MockExpandableListView(MockExpandableAdapter(groups, children, child_selectable=False))
    act2 = {
        "selectable_true_click": elv.click_child(1, 0),
        "selectable_false_click": elv_blocked.click_child(1, 0),
    }
    exp2 = {
        "selectable_true_click": "你点击了:提莫",
        "selectable_false_click": None,
    }

    # Case 3: Separate group/child ViewHolder recycling pools
    g0 = adapter.get_group_view(0, True)
    adapter.group_scrap.append(g0)
    g1 = adapter.get_group_view(1, False)
    c0 = adapter.get_child_view(0, 0)
    adapter.child_scrap.append(c0)
    c3 = adapter.get_child_view(0, 3)
    act3 = {
        "group_inflates": adapter.group_inflates,
        "child_inflates": adapter.child_inflates,
        "reused_group": g1,
        "reused_last_child": c3,
    }
    exp3 = {
        "group_inflates": 1,
        "child_inflates": 1,
        "reused_group": {"holder": "ViewHolderGroup", "text": "AP", "expanded": False},
        "reused_last_child": {"holder": "ViewHolderItem", "text": "韦鲁斯", "is_last": True},
    }

    # Case 4: XML layout attribute verification
    main_xml = """
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android">
        <ExpandableListView android:id="@+id/exlist_lol" android:childDivider="#E02D2F" />
    </RelativeLayout>
    """
    child_xml = """
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:background="#6BBA79">
        <ImageView android:id="@+id/img_icon" android:focusable="false" />
        <TextView android:id="@+id/tv_name" android:focusable="false" />
    </LinearLayout>
    """
    elv_node = ET.fromstring(main_xml).find("ExpandableListView")
    c_root = ET.fromstring(child_xml)
    act4 = {
        "childDivider": elv_node.attrib[ANDROID_NS + "childDivider"],
        "child_bg": c_root.attrib[ANDROID_NS + "background"],
        "children_focusable": [
            c_root.find("ImageView").attrib[ANDROID_NS + "focusable"],
            c_root.find("TextView").attrib[ANDROID_NS + "focusable"],
        ],
    }
    exp4 = {
        "childDivider": "#E02D2F",
        "child_bg": "#6BBA79",
        "children_focusable": ["false", "false"],
    }

    cases = [
        {
            "name": "group_child_hierarchy_and_packed_positions",
            "summary": "验证 3 组 14 项的折叠展开平铺投影与 64 位 packedPosition 编解码",
            "expected": exp1,
            "actual": act1,
            "passed": act1 == exp1,
        },
        {
            "name": "is_child_selectable_gate",
            "summary": "验证 isChildSelectable 返回 true/false 对 OnChildClickListener 触发的决定作用",
            "expected": exp2,
            "actual": act2,
            "passed": act2 == exp2,
        },
        {
            "name": "dual_viewholder_recycling",
            "summary": "验证 BaseExpandableListAdapter 分组视图与子项视图各自独立 ViewHolder 复用",
            "expected": exp3,
            "actual": act3,
            "passed": act3 == exp3,
        },
        {
            "name": "layout_and_divider_attributes",
            "summary": "解析 ExpandableListView 与子项布局 XML,核对 childDivider 及子控件 focusable 设置",
            "expected": exp4,
            "actual": act4,
            "passed": act4 == exp4,
        },
    ]
    print(
        json.dumps(
            {
                "version": "CPython 3.12.14 offline Android UI/Event/Handler verifier (Android SDK/emulator absent)",
                "cases": cases,
            },
            ensure_ascii=False,
            indent=2,
        )
    )


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/android-tutorial-expandablelistview-lab/explore-tutorial-expandablelistview.py

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

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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