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

运行 AutoCompleteTextView 前缀过滤、阈值控制与 CommaTokenizer 分词补全离线验证

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-autocompletetextview.py
explore-tutorial-autocompletetextview.py187 行
"""Offline Android verifier for Ch44: AutoCompleteTextView & MultiAutoCompleteTextView."""
import json
import xml.etree.ElementTree as ET

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


def array_adapter_filter(items: list[str], constraint: str, threshold: int = 1) -> list[str]:
    """Model Android ArrayAdapter.ArrayFilter: whole-string or word-start case-insensitive prefix match."""
    if len(constraint) < threshold:
        return []
    prefix = constraint.lower()
    matched = []
    for item in items:
        lower_item = item.lower()
        if lower_item.startswith(prefix):
            matched.append(item)
        else:
            words = lower_item.split(" ")
            if any(w.startswith(prefix) for w in words):
                matched.append(item)
    return matched


class CommaTokenizer:
    """Model MultiAutoCompleteTextView.CommaTokenizer."""

    def find_token_start(self, text: str, cursor: int) -> int:
        i = cursor
        while i > 0 and text[i - 1] != ",":
            i -= 1
        while i < cursor and text[i] == " ":
            i += 1
        return i

    def find_token_end(self, text: str, cursor: int) -> int:
        i = cursor
        n = len(text)
        while i < n:
            if text[i] == ",":
                return i
            i += 1
        return n

    def terminate_token(self, token: str) -> str:
        i = len(token)
        while i > 0 and token[i - 1] == " ":
            i -= 1
        if i > 0 and token[i - 1] == ",":
            return token
        return token + ", "


def apply_multi_completion(current_text: str, cursor: int, selected: str, tok: CommaTokenizer) -> str:
    start = tok.find_token_start(current_text, cursor)
    end = tok.find_token_end(current_text, cursor)
    return current_text[:start] + tok.terminate_token(selected) + current_text[end:]


def main() -> None:
    data = ["小猪猪", "小狗狗", "小鸡鸡", "小猫猫", "小咪咪"]

    # Case 1: completionThreshold & prefix filtering (non-prefix substring does not match)
    act1 = {
        "threshold_1_xiao": array_adapter_filter(data, "小", threshold=1),
        "threshold_2_xiao": array_adapter_filter(data, "小", threshold=2),
        "threshold_1_xiaomao": array_adapter_filter(data, "小猫", threshold=1),
        "middle_substring_zhuzhu": array_adapter_filter(data, "猪猪", threshold=1),
    }
    exp1 = {
        "threshold_1_xiao": ["小猪猪", "小狗狗", "小鸡鸡", "小猫猫", "小咪咪"],
        "threshold_2_xiao": [],
        "threshold_1_xiaomao": ["小猫猫"],
        "middle_substring_zhuzhu": [],
    }

    # Case 2: Word-boundary prefix matching in ArrayFilter
    en_items = ["Android Studio", "Hello Droid", "Kotlin Multiplatform"]
    act2 = {
        "match_droid": array_adapter_filter(en_items, "droid", threshold=1),
        "no_match_roid": array_adapter_filter(en_items, "roid", threshold=1),
        "match_multi": array_adapter_filter(en_items, "MULTI", threshold=2),
    }
    exp2 = {
        "match_droid": ["Hello Droid"],
        "no_match_roid": [],
        "match_multi": ["Kotlin Multiplatform"],
    }

    # Case 3: MultiAutoCompleteTextView with CommaTokenizer
    tok = CommaTokenizer()
    step1_text = "小"
    step1_cands = array_adapter_filter(data, step1_text, threshold=1)
    after_first = apply_multi_completion(step1_text, len(step1_text), step1_cands[0], tok)

    step2_text = after_first + "小猫"
    tok_start = tok.find_token_start(step2_text, len(step2_text))
    current_token = step2_text[tok_start:]
    step2_cands = array_adapter_filter(data, current_token, threshold=1)
    after_second = apply_multi_completion(step2_text, len(step2_text), step2_cands[0], tok)

    act3 = {
        "after_first": after_first,
        "second_token_extracted": current_token,
        "step2_cands": step2_cands,
        "after_second": after_second,
    }
    exp3 = {
        "after_first": "小猪猪, ",
        "second_token_extracted": "小猫",
        "step2_cands": ["小猫猫"],
        "after_second": "小猪猪, 小猫猫, ",
    }

    # Case 4: XML layout attributes audit
    xml_doc = """
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical">
        <AutoCompleteTextView android:id="@+id/atv_content"
            android:completionHint="请输入搜索内容"
            android:completionThreshold="1"
            android:dropDownHorizontalOffset="5dp" />
        <MultiAutoCompleteTextView android:id="@+id/matv_content"
            android:completionThreshold="1"
            android:dropDownHorizontalOffset="5dp" />
    </LinearLayout>
    """
    root = ET.fromstring(xml_doc)
    atv = root.find("AutoCompleteTextView")
    matv = root.find("MultiAutoCompleteTextView")
    act4 = {
        "atv_hint": atv.attrib[ANDROID_NS + "completionHint"],
        "atv_threshold": int(atv.attrib[ANDROID_NS + "completionThreshold"]),
        "atv_offset": atv.attrib[ANDROID_NS + "dropDownHorizontalOffset"],
        "matv_threshold": int(matv.attrib[ANDROID_NS + "completionThreshold"]),
    }
    exp4 = {
        "atv_hint": "请输入搜索内容",
        "atv_threshold": 1,
        "atv_offset": "5dp",
        "matv_threshold": 1,
    }

    cases = [
        {
            "name": "threshold_and_prefix_filter",
            "summary": "验证 completionThreshold 阈值控制与前缀匹配规则(中间子串不命中)",
            "expected": exp1,
            "actual": act1,
            "passed": act1 == exp1,
        },
        {
            "name": "word_boundary_prefix_matching",
            "summary": "验证 ArrayAdapter.ArrayFilter 对空格分词词首的忽略大小写前缀匹配",
            "expected": exp2,
            "actual": act2,
            "passed": act2 == exp2,
        },
        {
            "name": "multi_autocomplete_comma_tokenizer",
            "summary": "验证 MultiAutoCompleteTextView 配合 CommaTokenizer 连续补全多项内容",
            "expected": exp3,
            "actual": act3,
            "passed": act3 == exp3,
        },
        {
            "name": "dropdown_xml_attributes_check",
            "summary": "解析布局 XML 核对 completionHint、completionThreshold 与水平偏移属性",
            "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-autocompletetextview-lab/explore-tutorial-autocompletetextview.py

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

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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