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

运行 Spinner 首次默认回调拦截、XML 数组资源与自定义适配器离线验证

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-spinner.py
explore-tutorial-spinner.py186 行
"""Offline Android verifier for Ch43: Spinner selection guard, XML arrays & custom Adapter."""
import json
import xml.etree.ElementTree as ET
from dataclasses import dataclass


@dataclass(frozen=True)
class Hero:
    icon: str
    name: str


class MockSpinner:
    def __init__(self, spinner_id: str, mode: str, items: list, prompt: str | None = None):
        if mode not in ("dropdown", "dialog"):
            raise ValueError(f"Unsupported spinnerMode: {mode}")
        if prompt is not None and not prompt.startswith("@string/"):
            raise ValueError("android:prompt must reference a string resource ID")
        self.spinner_id = spinner_id
        self.mode = mode
        self.items = items
        self.prompt = prompt
        self.selected_position = -1
        self._listener = None

    def set_on_item_selected_listener(self, listener) -> None:
        self._listener = listener
        # Android Spinner auto-selects position 0 after layout/adapter attach
        if self.items:
            self.set_selection(0)

    def set_selection(self, position: int) -> None:
        if not (0 <= position < len(self.items)):
            raise IndexError("Selection out of bounds")
        self.selected_position = position
        if self._listener is not None:
            self._listener(self.spinner_id, position, self.items[position])


def main() -> None:
    # Case 1: Spinner initial setSelection(0) callback guard
    ranks_xml = """
    <resources>
        <string-array name="data">
            <item>英勇青铜</item>
            <item>不屈白银</item>
            <item>荣耀黄金</item>
            <item>华贵铂金</item>
            <item>璀璨钻石</item>
            <item>超凡大师</item>
            <item>最强王者</item>
        </string-array>
    </resources>
    """
    ranks = [el.text for el in ET.fromstring(ranks_xml).findall("./string-array/item")]
    guard_flags = {"spin_one": False, "spin_two": False}
    toasts: list[str] = []

    def on_item_selected(sid: str, pos: int, item) -> None:
        if sid == "spin_one":
            if guard_flags["spin_one"]:
                toasts.append(f"您的分段是~:{item}")
            else:
                guard_flags["spin_one"] = True
        elif sid == "spin_two":
            if guard_flags["spin_two"]:
                toasts.append(f"您选择的英雄是~:{item.name}")
            else:
                guard_flags["spin_two"] = True

    spin_one = MockSpinner("spin_one", "dialog", ranks, prompt="@string/spin_title")
    spin_one.set_on_item_selected_listener(on_item_selected)
    toasts_after_init = list(toasts)
    spin_one.set_selection(2)
    spin_one.set_selection(6)
    act1 = {
        "toasts_after_init": toasts_after_init,
        "toasts_after_user_pick": list(toasts),
        "selected_index": spin_one.selected_position,
    }
    exp1 = {
        "toasts_after_init": [],
        "toasts_after_user_pick": ["您的分段是~:荣耀黄金", "您的分段是~:最强王者"],
        "selected_index": 6,
    }

    # Case 2: XML string-array & prompt resource ID validation
    prompt_rejected = False
    try:
        MockSpinner("bad", "dialog", ranks, prompt="直接硬编码标题")
    except ValueError:
        prompt_rejected = True
    act2 = {
        "array_count": len(ranks),
        "first_and_last": [ranks[0], ranks[-1]],
        "literal_prompt_rejected": prompt_rejected,
        "mode": spin_one.mode,
    }
    exp2 = {
        "array_count": 7,
        "first_and_last": ["英勇青铜", "最强王者"],
        "literal_prompt_rejected": True,
        "mode": "dialog",
    }

    # Case 3: Custom Hero Adapter dropdown Spinner
    heroes = [
        Hero("mipmap/iv_lol_icon1", "迅捷斥候:提莫(Teemo)"),
        Hero("mipmap/iv_lol_icon2", "诺克萨斯之手:德莱厄斯(Darius)"),
        Hero("mipmap/iv_lol_icon3", "无极剑圣:易(Yi)"),
        Hero("mipmap/iv_lol_icon4", "荣耀行刑官:德莱文(Draven)"),
        Hero("mipmap/iv_lol_icon5", "德邦总管:赵信(XinZhao)"),
        Hero("mipmap/iv_lol_icon6", "狂战士:奥拉夫(Olaf)"),
    ]
    toasts.clear()
    spin_two = MockSpinner("spin_two", "dropdown", heroes)
    spin_two.set_on_item_selected_listener(on_item_selected)
    spin_two.set_selection(2)
    act3 = {
        "hero_count": len(heroes),
        "default_mode": spin_two.mode,
        "emitted_toasts": list(toasts),
    }
    exp3 = {
        "hero_count": 6,
        "default_mode": "dropdown",
        "emitted_toasts": ["您选择的英雄是~:无极剑圣:易(Yi)"],
    }

    # Case 4: Deprecated Gallery vs recycled horizontal list allocation comparison
    total_slides = 12
    visible_slots = 3
    gallery_view_allocations = total_slides  # recreates on each switch
    recycled_view_allocations = visible_slots + 1  # bounded scrap pool
    act4 = {
        "gallery_allocs": gallery_view_allocations,
        "recycled_allocs": recycled_view_allocations,
        "saved_allocs": gallery_view_allocations - recycled_view_allocations,
    }
    exp4 = {"gallery_allocs": 12, "recycled_allocs": 4, "saved_allocs": 8}

    cases = [
        {
            "name": "spinner_initial_selection_guard",
            "summary": "验证 Spinner 首次默认触发 onItemSelected 被布尔标志拦截,后续用户选择正常回调",
            "expected": exp1,
            "actual": act1,
            "passed": act1 == exp1,
        },
        {
            "name": "xml_string_array_dialog_spinner",
            "summary": "解析 string-array 数据源并验证 dialog 模式下 android:prompt 必须引用资源 ID",
            "expected": exp2,
            "actual": act2,
            "passed": act2 == exp2,
        },
        {
            "name": "custom_hero_adapter_dropdown",
            "summary": "验证自定义 BaseAdapter 驱动的 dropdown 模式 Spinner 项绑定与选中文本读取",
            "expected": exp3,
            "actual": act3,
            "passed": act3 == exp3,
        },
        {
            "name": "gallery_deprecation_replacement_comparison",
            "summary": "对比已弃用 Gallery 每次重建视图与复用容器在 12 页切换下的视图分配次数",
            "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-spinner-lab/explore-tutorial-spinner.py

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

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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