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

2.4.5 ListView简单实用

核对 Android ListView 搭配自定义 BaseAdapter 的入门实现、HeaderView/FooterView 添加顺序与位置偏移规律、分隔线配置、stackFromBottom、cacheColorHint 及隐藏滚动条属性,并对照 RecyclerView 演进。

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

学完这一章,你能够

自定义 BaseAdapter 与 ListView 基础绑定

`ListView` 是 Android 最经典的纵向滚动列表控件之一(在现代 Android 开发中已由性能更强、布局灵活的 `RecyclerView` 全面接替,但理解 `ListView` 仍是读懂存量工程与适配器原理的基础)。编写最简自定义适配器只需三步:定义实体类(如含 `aName`、`aSpeak`、`aIcon` 的 `Animal`);继承 `BaseAdapter` 重写 `getCount()`(返回数据条数)、`getItem(int position)`(返回对应数据对象)、`getItemId(int position)`(返回行 ID)与 `getView(int position, View convertView, ViewGroup parent)`(加载条目布局并填充控件);最后在 `Activity` 中组装 `LinkedList<Animal>` 并调用 `listView.setAdapter(adapter)` 完成绑定(该入门写法每行均重新 `inflate`,复用优化将在下一章展开)。

表头表尾、分隔线与 position 偏移规律

`ListView` 支持通过 XML 配置分隔线样式:`divider`(颜色或 Drawable)、`dividerHeight`(分隔线高度)、`headerDividersEnabled` 与 `footerDividersEnabled`(是否在表头/表尾边界绘制分隔线,默认均为 `true`)。表头与表尾需在代码中动态加载布局后调用 `addHeaderView(View v)` / `addFooterView(View v)` 添加,其三参数重载 `addHeaderView(v, data, isSelectable)` 可将 `isSelectable` 设为 `false` 禁用表头/表尾点击响应。需牢记两条重要坑点:第一,在 Android 4.4(API 19)之前的系统版本中,`addHeaderView()` 必须在 `setAdapter()` **之前**调用,否则会抛出 `IllegalStateException`;第二,添加表头后 `ListView` 内部会用 `HeaderViewListAdapter` 包装原适配器,`OnItemClickListener` 回调的 `position` 从表头 `0` 起算,原第 `0` 条业务数据会偏移至 `position = getHeaderViewsCount()`(例如添加 1 个表头后首条数据下标变为 `1`)。本站实验完整验证了 API 18 顺序守卫、总条目数 `1 + 5 + 1 = 7` 以及点击表头拦截与首条业务项 `position = 1` 偏移。

底部锚定、拖动黑底修正与隐藏滚动条

三项常见实用配置值得掌握:第一,聊天记录等场景希望列表初始停留在最底端,可配置 `android:stackFromBottom="true"`;第二,早期系统为 `ListView` 设置自定义背景图时,拖动或点击空白处易出现黑色底色闪烁,可将 `android:cacheColorHint="#00000000"` 设为全透明消除;第三,若要隐藏右侧垂直滚动条,可在 XML 中设 `android:scrollbars="none"`,或在 Java 代码中调用 `listView.setVerticalScrollBarEnabled(false)`(注:参考原文此处误写为传 `true`,实际传 `false` 才是隐藏滚动条)。

运行离线 ListView AnimalAdapter 绑定、Header/Footer 顺序与偏移及滚动条属性核验

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 验证 5 条数据绑定、API<19 后置 addHeaderView 报错、表头偏移使首条数据位于 position=1 及 setVerticalScrollBarEnabled(false) 纠偏。
运行离线 ListView AnimalAdapter 绑定、Header/Footer 顺序与偏移及滚动条属性核验

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

当前源码 SHA256:4f517948bbb656d687a8f7c3476a68a2c372f6fe17dff323365cd5455ca7d864

下载本站示例源码

本地运行

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

下载2.4.5 ListView简单实用实验

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

ZIP SHA256:6fcf164b9c44bb641b8fdfa42abe7907d1d2de747a3057b3d2e5a612678c1232

常见错误与边界

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

练习与解答

给 `ListView` 添加了 2 个 `HeaderView` 之后,用户在 `OnItemClickListener` 中点击了第 1 条真实业务数据时,回调参数 `position` 的值是多少?应如何安全取得对应数据索引?

展开参考解答

`position` 的值是 `2`(`0` 和 `1` 对应两个表头);应通过 `int dataIndex = position - listView.getHeaderViewsCount()` 换算真实业务数据下标,并在访问前判断 `dataIndex >= 0 && dataIndex < mData.size()`。

规范与官方依据