2.3.2 EditText(输入框)详解
核对 Android EditText 的默认提示文本、焦点全选、inputType 输入类型、行数限制、大写控制、软键盘 windowSoftInputMode、光标选区控制、表情图文插入及带清空按钮的自定义输入框实现。
学完这一章,你能够
- 核对 Android EditText 的默认提示文本、焦点全选、inputType 输入类型、行数限制、大写控制、软键盘 windowSoftInputMode、光标选区控制、表情图文插入及带清空按钮的自定义输入框实现。
提示文本、焦点全选与输入类型限制
`EditText` 继承自 `TextView`,核心区别在于能够接收与编辑用户输入。在登录、搜索等表单场景中,通常借助 `android:hint` 设置输入框为空时的引导提示文案,并以 `android:textColorHint` 统一提示文字颜色,从而省去冗余的外部标签。
当输入框已有默认值、希望用户点按聚焦后直接全选便于一次性覆盖改写时,可在 XML 中配置 `android:selectAllOnFocus="true"`(或在代码中调用 `setSelectAllOnFocus(true)`),替代默认将光标置于首尾的行为。
借助 `android:inputType` 可同时约束合法输入字符与软键盘面板形态,分为文本类(如 `text`、`textCapCharacters`、`textCapWords`、`textCapSentences`、`textAutoCorrect`、`textAutoComplete`、`textMultiLine`、`textImeMultiLine`、`textNoSuggestions`、`textUri`、`textEmailAddress`、`textEmailSubject`、`textShortMessage`、`textLongMessage`、`textPersonName`、`textPostalAddress`、`textPassword`、`textVisiblePassword`、`textWebEditText`、`textFilter`、`textPhonetic`、`none`)与数值/日期类(如 `number`、`numberSigned`、`numberDecimal`、`phone` 拨号键盘、`datetime`、`date`、`time`),多项标志可用 `|` 组合。
行数控制、字距大写与内外边距
`EditText` 默认允许多行输入并自动折行。通过 `android:minLines` 与 `android:maxLines` 可限定最小显示行高与最大可见行数(超出最大行数后文本自动纵向滚动);登录账号等单行场景则可设置 `android:singleLine="true"`(现代写法推荐 `android:maxLines="1"` 配合不含 `textMultiLine` 的 `inputType`)禁止折行。
排版细节方面:`android:textScaleX` 控制字符水平缩放比例(需注意 Android `TextView`/`EditText` 并无 `android:textScaleY` 属性,行间垂直距离应使用 `lineSpacingExtra` 与 `lineSpacingMultiplier`);英文字母自动大写早期通过 `android:capitalize` 设置 `none`/`sentences`(句首大写)/`words`(词首大写)/`characters`(全大写),现行 API 已推荐改用 `inputType` 中的 `textCapSentences`/`textCapWords`/`textCapCharacters`。控件外边距与内边距分别由 `android:layout_margin*`(控制与相邻控件或父容器的间距)和 `android:padding*`(控制内部文字与边框的间距)控制。
焦点获取、软键盘控制与光标选区
代码中可通过 `requestFocus()` 与 `clearFocus()` 控制输入框焦点,并通过 `InputMethodManager` 的 `toggleSoftInput()`、`showSoftInput()` 与 `hideSoftInputFromWindow()` 显隐软键盘。但在页面刚创建尚未完成窗口附着时,直接调用 `showSoftInput` 常会失效;为此可在 `AndroidManifest.xml` 中为对应 `Activity` 配置 `android:windowSoftInputMode`,将状态标志(`stateUnspecified`、`stateUnchanged`、`stateHidden`、`stateAlwaysHidden`、`stateVisible`、`stateAlwaysVisible`)与窗口缩放标志(`adjustUnspecified`、`adjustResize`、`adjustPan`)以 `|` 组合(例如 `stateAlwaysVisible|adjustResize`),在获得焦点时稳定唤起输入法并防止遮挡。
`EditText` 通过 `setSelection(int index)` 将光标定位至指定字符下标,通过 `setSelection(int start, int stop)` 选中 `[start, stop)` 区间的部分文本;此外可调用 `setCursorVisible(false)` 隐藏闪烁光标,并通过 `getSelectionStart()` 与 `getSelectionEnd()` 随时读取当前光标或选区边界。
图文表情插入与带清空图标的自定义输入框
在聊天输入框中插入表情图可采用 `SpannableString` + `ImageSpan` 或 `Html` 两种路径。前者构造占位串(如 `"imge"`),加载目标 `Drawable` 并设置 `setBounds(0, 0, intrinsicWidth, intrinsicHeight)`,包裹为 `ImageSpan(drawable, ImageSpan.ALIGN_BASELINE)` 绑定至占位区间后,读取当前光标 `edit.getSelectionStart()` 并调用 `edit.getText().insert(cursor, spanStr)` 即可在任意光标处精准插入表情(本站实验实测在 `"你好世界"` 索引 `2` 处插入后变为 `"你好imge世界"`,光标推进至 `6`)。
常见的“一键清空”搜索框可通过继承 `EditText` 封装 `EditTextWithDel` 实现:注册 `TextWatcher` 在 `afterTextChanged()` 中检查当前文本长度,非空时借助 `setCompoundDrawablesWithIntrinsicBounds(null, null, imgDel, null)` 在右侧显示清除图标,为空时移除;再重写 `onTouchEvent()`,在 `MotionEvent.ACTION_UP` 时结合 `getGlobalVisibleRect(rect)` 判定触点是否落在右侧删除图标区域(`rect.right - 100` 至 `rect.right`),命中即执行 `setText("")` 清空并自动隐藏图标(现代 Material Design 工程也可直接使用 `TextInputLayout` 的 `endIconMode="clear_text"`)。
运行离线 EditText 属性解析、inputType/软键盘模式校验、光标表情插入与一键清空命中测试
展开查看收起
"""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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
可将该 `Activity` 的 `android:windowSoftInputMode` 设为 `stateAlwaysVisible|adjustResize`(或根据布局需要选用 `stateVisible|adjustPan`),再配合目标 `EditText.requestFocus()` 触发输入法面板。