2.5.4 AutoCompleteTextView(自动完成文本框)的基本使用
讲解 AutoCompleteTextView 与 MultiAutoCompleteTextView 的常用属性、ArrayAdapter 前缀过滤规则,以及 CommaTokenizer 多项连续补全机制。
学完这一章,你能够
- 讲解 AutoCompleteTextView 与 MultiAutoCompleteTextView 的常用属性、ArrayAdapter 前缀过滤规则,以及 CommaTokenizer 多项连续补全机制。
自动完成文本框定位与核心 XML 属性
`AutoCompleteTextView`(自动完成文本框)继承自 `EditText` 并与 `ListAdapter`/`Filterable` 协同工作,能在用户输入字符的同时弹出下拉候选项,且同样支持自定义候选条目的布局样式。
常用配置属性覆盖触发门槛与弹层外观:`android:completionThreshold` 指定至少输入多少个字符才触发下拉提示(默认 2,常设为 1);`android:completionHint` 与 `android:completionHintView` 控制提示列表底部的说明文案或自定义视图;`android:dropDownAnchor` 指定弹层定位锚点(缺省以当前文本框自身为锚点);`android:dropDownWidth`、`dropDownHeight`、`dropDownHorizontalOffset` 与 `dropDownVerticalOffset` 控制弹层尺寸及偏移;`android:dropDownSelector` 与 `android:popupBackground` 设置点击态与背景。
与之配套的 `MultiAutoCompleteTextView` 支持在同一输入框内通过分隔符连续补全多项内容。需要特别注意的是,系统默认 `ArrayAdapter` 内置的 `ArrayFilter` 采用**忽略大小写的整串前缀或空格分词词首前缀匹配**,而非任意中间子串匹配:例如候选词为 `"小猪猪"` 时,输入 `"小"` 可命中,输入中间片段 `"猪猪"` 则不会提示;若业务需要任意子串模糊搜索,须自定义实现 `Filterable` 的适配器。
单选与多项逗号分隔补全代码解析
在 `activity_main.xml` 中分别放置 `AutoCompleteTextView` 与 `MultiAutoCompleteTextView`,均设置 `completionThreshold="1"` 和 `dropDownHorizontalOffset="5dp"`,并为前者添加 `completionHint="请输入搜索内容"`。在 `MainActivity` 中使用系统内置布局 `android.R.layout.simple_dropdown_item_1line` 构造 `ArrayAdapter<String>` 绑定 5 组候选词,为 `matv_content` 额外调用 `setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer())` 启用英文逗号加空格的分词器(注意示例中创建了 `adapter2` 却将 `adapter` 复用于两个控件,实际开发中独立控件建议各自绑定独立适配器实例以避免共享过滤结果状态互相干扰)。
结合四处关键配置回顾要点:`completionThreshold="1"` 使键入首个字即弹出列表;`completionHint` 在候选区底部给出引导文字(可由 `completionHintView` 替换为自定义视图);`dropDownHorizontalOffset="5dp"` 微调下拉框水平边距;`CommaTokenizer` 会在每次选中候选词后自动补齐 `", "` 并以逗号为界提取下一段待补全词元。本站离线 Python 验证器完整建模了 `ArrayFilter` 词首前缀匹配、`completionThreshold` 阈值对比及 `CommaTokenizer` 的 `findTokenStart`/`findTokenEnd`/`terminateToken` 流程。
示例代码包与小结
原教程附带 `AutoCompleteTextViewDemo.zip` 供下载(因继承源站停采策略未联网抓取,已登记至 `reviewed_source_attachments`)。掌握阈值、适配器过滤规则与 `Tokenizer` 分隔器后,可轻松拓展出邮箱后缀提示、标签多选输入等实用组件。
运行 AutoCompleteTextView 前缀过滤、阈值控制与 CommaTokenizer 分词补全离线验证
"""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()
- 验证 threshold=1/2 过滤差异、中间子串不命中与词首命中规则,以及 CommaTokenizer 连续补全为 "小猪猪, 小猫猫, "。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:7aa8b03a800e1868752c015516c4f0cd7eacd45e6fc889198287f5b7c9043c0d
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:9904b149c5c55afcdc0998210bb574d50d55aede33519ad0e1ceeff50fb40dd5
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在默认 ArrayAdapter 下,AutoCompleteTextView 为什么输入 "猪猪" 匹配不到 "小猪猪"?如何支持中间子串匹配?
展开参考解答
因为默认 ArrayAdapter.ArrayFilter 只执行整串前缀和空格分词后的词首前缀匹配;若要支持任意子串匹配,需要自定义实现 Filterable 接口的 Adapter 并在 performFiltering() 中改用 contains() 过滤。