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

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

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-adapter.py
explore-tutorial-adapter.py141 行
"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

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

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

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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