蓝色天空网mbsky.com · 知识 · 实践 · 创造Android · 本地阅读预览
教程 / 移动开发 / Android

2.5.5 ExpandableListView(可折叠列表)的基本使用

系统梳理 ExpandableListView 的分组与子项指示器属性、三种 ExpandableListAdapter 实现途径,以及 BaseExpandableListAdapter 双层 ViewHolder 复用与 isChildSelectable 点击开关。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

可折叠列表定位与 XML 属性

`ExpandableListView` 直接继承自 `ListView`,在普通一维列表之上扩展出“分组(Group)—子项(Child)”两级树状折叠能力,外观类似于即时通信软件中的分组好友列表,数据由 `ExpandableListAdapter` 提供。

其专属 XML 属性围绕分隔线与展开/收起指示图标设计:`android:childDivider` 指定组内子项之间的分隔线颜色或 Drawable;`android:groupIndicator` 与 `android:childIndicator` 分别定义分组和子项旁边的指示器图标;`indicatorLeft` / `indicatorRight` / `indicatorStart` / `indicatorEnd` 以及对应的 `childIndicatorLeft` / `Right` / `Start` / `End` 用于精确约束指示器在水平方向上的边界位置(`Start`/`End` 兼容从右到左 RTL 排版)。

实现 ExpandableListAdapter 的三种途径

为 `ExpandableListView` 提供分组数据时有三种标准方式:第一,继承抽象基类 `BaseExpandableListAdapter`(灵活度最高,也是本节示例采用的方式);第二,使用 `SimpleExpandableListAdapter` 将两层 `List<Map>` 数据结构直接映射到布局;第三,使用 `SimpleCursorTreeAdapter` 将数据库查询得到的 `Cursor` 包装为两级列表。

BaseExpandableListAdapter 完整示例与关键要点

自定义 `BaseExpandableListAdapter` 与普通 `BaseAdapter` 思路一致,但将计数、数据读取与视图创建拆分为组(`getGroupCount`、`getGroup`、`getGroupId`、`getGroupView`)和子项(`getChildrenCount`、`getChild`、`getChildId`、`getChildView`)两套方法。**务必注意**:必须将 `isChildSelectable(int groupPosition, int childPosition)` 重写为返回 `true`,否则框架会禁止选中子项,导致 `OnChildClickListener` 永远不会被触发。

示例中先定义分组行布局 `item_exlist_group.xml` 与子项行布局 `item_exlist_item.xml`(子项内 `ImageView` 与 `TextView` 设置 `android:focusable="false"` 以防抢占点击焦点),再编写 `MyBaseExpandableListAdapter` 分别通过 `ViewHolderGroup` 与 `ViewHolderItem` 缓存两类 `convertView`;子列表数据结构不一定局限于 `ArrayList<ArrayList<Item>>`,也可按业务封装在分组实体类内部(如 `Group` 对象持有 `List<Item>`)。

主布局 `activity_main.xml` 声明 `ExpandableListView` 并设置红色 `childDivider="#E02D2F"`;`MainActivity` 初始化 `AD`(4 项)、`AP`(5 项)、`TANK`(5 项)共 3 组 14 条记录并注册 `setOnChildClickListener()`,在点击子项时通过 `groupPosition` 与 `childPosition` 定位实体弹出提示。本站离线 Python 脚本建模了分组折叠/展开平铺投影、Android 64 位 `packedPosition` 编解码、`isChildSelectable` 开关及双池 ViewHolder 复用。

示例代码包与小结

原教程提供 `ExpandableListViewDemo.zip` 示例包(因继承停采策略未联网下载,已登记至 `reviewed_source_attachments`)。理解两级索引映射与 `isChildSelectable()` 机制后,即可应对多数二级分类折叠菜单需求。

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

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 验证 3 组 14 项展开/收起平铺行数、packedPosition 编解码、isChildSelectable=false 阻断点击及双池 ViewHolder 复用。
运行 ExpandableListView 分组展开投影、64 位 packedPosition 与点击开关离线验证

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

当前源码 SHA256:2d35fa66149c15cb85a9618f72038b1ffaf45f63373a7b97804dad250447cf03

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载2.5.5 ExpandableListView(可折叠列表)的基本使用实验

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

ZIP SHA256:ef9e55c21b364b4ee5d7a85f1fdb1e1b7e13331948f1d94d6ba81c59906de3d3

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在继承 BaseExpandableListAdapter 后,为什么有时注册了 setOnChildClickListener 却点击子项毫无反应?

展开参考解答

通常是因为未将 isChildSelectable(groupPosition, childPosition) 重写为返回 true,或子项布局内部的按钮/控件抢占了焦点而未设置 focusable="false"。

规范与官方依据