Android Studio:实现文本框文字自动完成功能
要实现输入文本框中的文字自动完成显示,可以使用 'AutoCompleteTextView' 控件。
- 在布局文件中添加 'AutoCompleteTextView' 控件:
<AutoCompleteTextView
android:id="@+id/autoCompleteTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:completionThreshold="1" />
- 创建一个字符串数组,包含可选的文字选项:
String[] options = {'Option 1', 'Option 2', 'Option 3'};
- 在 Activity 中获取 'AutoCompleteTextView' 控件的实例,并为其设置适配器:
AutoCompleteTextView autoCompleteTextView = findViewById(R.id.autoCompleteTextView);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, options);
autoCompleteTextView.setAdapter(adapter);
- 现在当用户在输入文本框中输入文字时,将会显示匹配的选项供用户选择。
注意:在设置适配器之前,可以通过 'setThreshold' 方法设置输入文本的最小长度,以触发自动完成功能。在上述示例中,设置了 android:completionThreshold="1",表示只要用户输入了一个字符,就会触发自动完成功能。
原文地址: https://www.cveoy.top/t/topic/qlEh 著作权归作者所有。请勿转载和采集!