蓝色天空.知识 · 实践 · 创造
我的收藏
Android 教程目录 156章
课程介绍
Android / LEARN BY DOING

2.4.4 Adapter基础讲解

核对 MVC 架构中 Adapter 适配器的控制器定位、Adapter 继承体系以及 ArrayAdapter、SimpleAdapter、SimpleCursorAdapter 三种内置适配器的用法、约束与现代 RecyclerView.Adapter 演进。

学完这一章,你能够

  • 核对 MVC 架构中 Adapter 适配器的控制器定位、Adapter 继承体系以及 ArrayAdapter、SimpleAdapter、SimpleCursorAdapter 三种内置适配器的用法、约束与现代 RecyclerView.Adapter 演进。

MVC 分层思想与 Adapter 继承体系

`Adapter`(适配器)是连接底层数据源与列表/网格类 UI 控件的桥梁,负责按条目结构把数据填充到对应视图中。对照经典 MVC(Model-View-Controller)分工:`Model` 承载业务数据与计算逻辑,`View` 负责图形界面展示与交互入口,`Controller` 调度数据与界面的协作流程;在 Android `AdapterView` 体系里,`Adapter` 正扮演中间 `Controller` 的角色(`Model -> Adapter -> View`),使数据变更与界面排版彼此解耦。

在 `Adapter` 继承树下,传统开发最常接触四类实现:`BaseAdapter`(抽象基类,自由度最高,业务中最常继承重写)、`ArrayAdapter<T>`(支持泛型的轻量单文本列表适配器)、`SimpleAdapter`(通过 `List<Map<String, Object>>` 将键值映射到自定义行布局中多个控件)以及 `SimpleCursorAdapter`(直接绑定数据库或 `ContentProvider` 返回的 `Cursor`,现已因主线程查询风险而过时,推荐使用异步查询 + `BaseAdapter` 或现代 `RecyclerView.Adapter` + `ListAdapter`/`DiffUtil`)。

ArrayAdapter、SimpleAdapter 与 SimpleCursorAdapter 实测要点

`ArrayAdapter` 接受 Java 数组、`List<T>` 泛型集合或 XML `<string-array>` 资源:既可在 `res/values/arrays.xml` 中定义数组并在 `<ListView android:entries="@array/myarray"/>` 直接静态声明,也可通过 `ArrayAdapter.createFromResource(context, R.array.myarray, layoutRes)` 动态创建。其第二个构造参数可直接复用系统内置行模板,包括 `simple_list_item_1`(单行文本)、`simple_list_item_2`(双行文本)、`simple_list_item_checked`(带勾选状态文本)、`simple_list_item_multiple_choice`(带多选框)与 `simple_list_item_single_choice`(带单选钮)。

`SimpleAdapter` 适合静态图文混排列表:先编写包含头像 `ImageView`、昵称与动态 `TextView` 的 `list_item.xml`,再将数据整理为 `List<Map<String, Object>>`,构造 `SimpleAdapter(context, listitem, R.layout.list_item, fromKeys, toViewIds)` 将 `from` 键名数组与 `to` 控件 ID 数组一一对齐绑定(本站实验核验了 `["touxiang", "name", "says"] -> ["imgtou", "name", "says"]` 三条记录的完整映射)。

`SimpleCursorAdapter` 可把 `ContentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, ...)` 获取的联系人 `Cursor` 列(`DISPLAY_NAME`、`NUMBER`)直接映射到行布局的文本框中(须在清单文件声明 `<uses-permission android:name="android.permission.READ_CONTACTS"/>`,且 Android 6.0+ 需动态申请运行时权限)。使用 `CursorAdapter` 家族必须满足一项核心约束:结果集 `Cursor` 中**必须包含名为 `_id` 的主键列**(若原表主键名为 `id` 须在 SQL 中写 `id AS _id`),否则系统会抛出 `IllegalArgumentException: column '_id' does not exist`。日常业务仍以继承 `BaseAdapter`(或现代 `RecyclerView.Adapter`)为主流实践。

运行离线 ArrayAdapter XML/模板解析、SimpleAdapter 键值绑定与 SimpleCursorAdapter _id 约束核验

含完整源码 · 141 行
展开查看收起
python
"""Offline Android UI verifier for Ch 34: Adapter Basics."""
import json
import xml.etree.ElementTree as ET

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

ARRAYS_XML = """<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="myarray">
        <item>语文</item>
        <item>数学</item>
        <item>英语</item>
    </string-array>
</resources>
"""

SIMPLE_ITEM_XML = """<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal">
    <ImageView android:id="@+id/imgtou" android:layout_width="64dp" android:layout_height="64dp" />
    <LinearLayout android:orientation="vertical">
        <TextView android:id="@+id/name" android:textSize="20sp" />
        <TextView android:id="@+id/says" android:textSize="14sp" />
    </LinearLayout>
</LinearLayout>
"""


def bind_simple_cursor(columns: list, rows: list, from_cols: list, to_ids: list) -> dict:
    if "_id" not in columns:
        return {"ok": False, "error": "IllegalArgumentException: column '_id' does not exist"}
    col_idx = {c: i for i, c in enumerate(columns)}
    bound = []
    for r in rows:
        bound.append({vid: r[col_idx[col]] for col, vid in zip(from_cols, to_ids)})
    return {"ok": True, "bound": bound}


def main() -> None:
    arr_root = ET.fromstring(ARRAYS_XML)
    xml_items = [it.text for it in arr_root.find("string-array").findall("item")]
    builtin_layouts = [
        "simple_list_item_1",
        "simple_list_item_2",
        "simple_list_item_checked",
        "simple_list_item_multiple_choice",
        "simple_list_item_single_choice",
    ]
    c1_actual = {
        "mvc_role": "Controller",
        "xml_string_array": xml_items,
        "builtin_layout_count": len(builtin_layouts),
        "generic_list_size": len(["成员A", "成员B"]),
    }
    c1_expected = {
        "mvc_role": "Controller",
        "xml_string_array": ["语文", "数学", "英语"],
        "builtin_layout_count": 5,
        "generic_list_size": 2,
    }

    # Case 2: SimpleAdapter key -> viewId mapping over list_item.xml
    item_root = ET.fromstring(SIMPLE_ITEM_XML)
    view_ids = [el.attrib[f"{ANDROID_NS}id"].split("/")[-1] for el in item_root.iter() if f"{ANDROID_NS}id" in el.attrib]
    data = [
        {"touxiang": "head_icon1", "name": "用户甲", "says": "专注性能优化"},
        {"touxiang": "head_icon2", "name": "用户乙", "says": "熟悉布局体系"},
        {"touxiang": "head_icon3", "name": "用户丙", "says": "擅长适配器封装"},
    ]
    from_keys = ["touxiang", "name", "says"]
    to_ids = ["imgtou", "name", "says"]
    rendered = [{vid: row[k] for k, vid in zip(from_keys, to_ids)} for row in data]
    c2_actual = {"xml_view_ids": view_ids, "rendered_rows": rendered}
    c2_expected = {
        "xml_view_ids": ["imgtou", "name", "says"],
        "rendered_rows": [
            {"imgtou": "head_icon1", "name": "用户甲", "says": "专注性能优化"},
            {"imgtou": "head_icon2", "name": "用户乙", "says": "熟悉布局体系"},
            {"imgtou": "head_icon3", "name": "用户丙", "says": "擅长适配器封装"},
        ],
    }

    # Case 3: SimpleCursorAdapter mandatory _id column invariant
    bad = bind_simple_cursor(["id", "display_name", "number"], [(1, "张三", "13800001111")], ["display_name", "number"], ["list_name", "list_phone"])
    good = bind_simple_cursor(["_id", "display_name", "number"], [(1, "张三", "13800001111")], ["display_name", "number"], ["list_name", "list_phone"])
    c3_actual = {"missing_underscore_id": bad, "with_underscore_id": good, "permission": "android.permission.READ_CONTACTS"}
    c3_expected = {
        "missing_underscore_id": {"ok": False, "error": "IllegalArgumentException: column '_id' does not exist"},
        "with_underscore_id": {"ok": True, "bound": [{"list_name": "张三", "list_phone": "13800001111"}]},
        "permission": "android.permission.READ_CONTACTS",
    }

    # Case 4: Adapter hierarchy & modern RecyclerView comparison
    c4_actual = {
        "base_adapter_subclasses": ["ArrayAdapter", "SimpleAdapter", "CursorAdapter"],
        "modern_replacement": "RecyclerView.Adapter + ListAdapter/DiffUtil",
    }
    c4_expected = {
        "base_adapter_subclasses": ["ArrayAdapter", "SimpleAdapter", "CursorAdapter"],
        "modern_replacement": "RecyclerView.Adapter + ListAdapter/DiffUtil",
    }

    cases = [
        {
            "name": "mvc_adapter_role_and_arrayadapter",
            "summary": "解析 arrays.xml 字符串数组、ArrayAdapter 5 种系统行模板及 Adapter 的 MVC 控制器角色",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "simpleadapter_key_to_view_binding",
            "summary": "解析 list_item.xml 并模拟 SimpleAdapter 从 Map 键到目标控件 ID 的逐行绑定",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
        {
            "name": "simplecursoradapter_id_column_invariant",
            "summary": "验证 SimpleCursorAdapter 强制要求 _id 主键列(缺失触发 IllegalArgumentException)与联系人权限声明",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        },
        {
            "name": "adapter_hierarchy_and_modern_mapping",
            "summary": "核对 BaseAdapter 核心子类族谱与现代 RecyclerView.Adapter/ListAdapter 演进对照",
            "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()
验证 arrays.xml 与 5 种内置行模板、SimpleAdapter 三行键值到 ID 绑定、缺失 _id 抛出 IllegalArgumentException 及 Adapter 继承体系。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

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

下载本章实验包 (mbskycom202612a1829.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

`CursorAdapter` 底层强制按列名 `_id` 读取行标识,缺少 `_id` 会抛出 `IllegalArgumentException: column '_id' does not exist`;修复方式是在 SQL 查询中使用别名 `SELECT user_id AS _id, ...`。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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