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

运行离线 EditText 属性解析、inputType/软键盘模式校验、光标表情插入与一键清空命中测试

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-edittext.py
explore-tutorial-edittext.py189 行
"""Offline Android UI verifier for Ch 23: EditText."""
import json
import re
import xml.etree.ElementTree as ET

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

EDITTEXT_XML = """<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">
    <EditText
        android:id="@+id/et_login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="默认提示文本"
        android:textColorHint="#95A1AA"
        android:selectAllOnFocus="true"
        android:singleLine="true"
        android:inputType="phone"
        android:textScaleX="1.5"
        android:layout_marginTop="5dp"
        android:paddingTop="5dp" />
    <EditText
        android:id="@+id/et_note"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minLines="3"
        android:maxLines="3"
        android:inputType="textMultiLine|textCapSentences" />
</LinearLayout>
"""

INPUT_TYPES = {
    "text": {"class": "TYPE_CLASS_TEXT", "masked": False, "keyboard": "qwerty"},
    "textPassword": {"class": "TYPE_CLASS_TEXT", "masked": True, "keyboard": "qwerty"},
    "textEmailAddress": {"class": "TYPE_CLASS_TEXT", "masked": False, "keyboard": "email"},
    "number": {"class": "TYPE_CLASS_NUMBER", "masked": False, "keyboard": "numeric"},
    "numberSigned": {"class": "TYPE_CLASS_NUMBER", "masked": False, "keyboard": "numeric_signed"},
    "numberDecimal": {"class": "TYPE_CLASS_NUMBER", "masked": False, "keyboard": "numeric_decimal"},
    "phone": {"class": "TYPE_CLASS_PHONE", "masked": False, "keyboard": "dialpad"},
    "date": {"class": "TYPE_CLASS_DATETIME", "masked": False, "keyboard": "date"},
    "time": {"class": "TYPE_CLASS_DATETIME", "masked": False, "keyboard": "time"},
}

SOFT_INPUT_STATE = {"stateUnspecified", "stateUnchanged", "stateHidden", "stateAlwaysHidden", "stateVisible", "stateAlwaysVisible"}
SOFT_INPUT_ADJUST = {"adjustUnspecified", "adjustResize", "adjustPan"}


def apply_capitalize(text: str, mode: str) -> str:
    if mode == "characters":
        return text.upper()
    if mode == "words":
        return " ".join(w[:1].upper() + w[1:] for w in text.split(" "))
    if mode == "sentences":
        return re.sub(r"(^|[.!?]\s+)([a-z])", lambda m: m.group(1) + m.group(2).upper(), text)
    return text


def main() -> None:
    root = ET.fromstring(EDITTEXT_XML)
    et_login, et_note = root[0], root[1]
    c1_actual = {
        "hint": et_login.attrib[f"{ANDROID_NS}hint"],
        "hint_color": et_login.attrib[f"{ANDROID_NS}textColorHint"],
        "select_all_on_focus": et_login.attrib[f"{ANDROID_NS}selectAllOnFocus"] == "true",
        "single_line": et_login.attrib[f"{ANDROID_NS}singleLine"] == "true",
        "note_line_bounds": [int(et_note.attrib[f"{ANDROID_NS}minLines"]), int(et_note.attrib[f"{ANDROID_NS}maxLines"])],
        "capitalize_modes": {
            "sentences": apply_capitalize("hello world. android ui.", "sentences"),
            "words": apply_capitalize("hello android world", "words"),
            "characters": apply_capitalize("hello android", "characters"),
        },
    }
    c1_expected = {
        "hint": "默认提示文本",
        "hint_color": "#95A1AA",
        "select_all_on_focus": True,
        "single_line": True,
        "note_line_bounds": [3, 3],
        "capitalize_modes": {
            "sentences": "Hello world. Android ui.",
            "words": "Hello Android World",
            "characters": "HELLO ANDROID",
        },
    }

    # Case 2: inputType & windowSoftInputMode flag parsing
    mode_str = "stateAlwaysVisible|adjustResize"
    flags = mode_str.split("|")
    state_flags = [f for f in flags if f in SOFT_INPUT_STATE]
    adjust_flags = [f for f in flags if f in SOFT_INPUT_ADJUST]
    c2_actual = {
        "phone_meta": INPUT_TYPES["phone"],
        "password_masked": INPUT_TYPES["textPassword"]["masked"],
        "decimal_class": INPUT_TYPES["numberDecimal"]["class"],
        "soft_input_parsed": {"state": state_flags, "adjust": adjust_flags, "valid_combo": len(state_flags) == 1 and len(adjust_flags) == 1},
    }
    c2_expected = {
        "phone_meta": {"class": "TYPE_CLASS_PHONE", "masked": False, "keyboard": "dialpad"},
        "password_masked": True,
        "decimal_class": "TYPE_CLASS_NUMBER",
        "soft_input_parsed": {"state": ["stateAlwaysVisible"], "adjust": ["adjustResize"], "valid_combo": True},
    }

    # Case 3: Cursor selection & SpannableString emoji insertion
    buf = "你好世界"
    sel_start, sel_end = 2, 2  # setSelection(2)
    emoji_token = "imge"
    buf = buf[:sel_start] + emoji_token + buf[sel_end:]
    new_cursor = sel_start + len(emoji_token)
    # setSelection(2, 6) selects inserted emoji span
    selected_slice = buf[2:6]
    c3_actual = {
        "after_insert": buf,
        "new_cursor": new_cursor,
        "selected_span": selected_slice,
    }
    c3_expected = {
        "after_insert": "你好imge世界",
        "new_cursor": 6,
        "selected_span": "imge",
    }

    # Case 4: EditTextWithDel TextWatcher + ACTION_UP hit-test
    text = ""
    visible_when_empty = len(text) >= 1
    text = "android"
    visible_when_typed = len(text) >= 1
    # Global visible rect: [0, 100, 400, 180], clear zone is [right - 100, right] = [300, 400]
    rect = {"left": 0, "top": 100, "right": 400, "bottom": 180}
    clear_left = rect["right"] - 100
    hit_outside = (clear_left <= 150 <= rect["right"]) and (rect["top"] <= 140 <= rect["bottom"])
    hit_inside = (clear_left <= 360 <= rect["right"]) and (rect["top"] <= 140 <= rect["bottom"])
    if hit_inside:
        text = ""
    c4_actual = {
        "icon_empty": visible_when_empty,
        "icon_typed": visible_when_typed,
        "hit_outside_clear_zone": hit_outside,
        "hit_inside_clear_zone": hit_inside,
        "text_after_clear": text,
        "icon_after_clear": len(text) >= 1,
    }
    c4_expected = {
        "icon_empty": False,
        "icon_typed": True,
        "hit_outside_clear_zone": False,
        "hit_inside_clear_zone": True,
        "text_after_clear": "",
        "icon_after_clear": False,
    }

    cases = [
        {
            "name": "edittext_xml_hint_focus_and_lines",
            "summary": "解析 EditText 提示文本、全选、行数限制属性及 capitalize 三种大小写转换",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "inputtype_validation_and_keyboard_mode",
            "summary": "核对 inputType 文本/数值/拨号分类与 windowSoftInputMode 组合标志解析",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
        {
            "name": "cursor_selection_and_emoji_insert",
            "summary": "模拟 EditText 光标定位、ImageSpan 占位串插入与范围选中",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        },
        {
            "name": "clearable_edittext_watcher_and_hit_test",
            "summary": "模拟带删除图标 EditText 的 TextWatcher 显隐联动与右侧区域点击清空判定",
            "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-edittext-lab/explore-tutorial-edittext.py

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

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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