java.lang.Object | ||||
↳ | android.view.View | |||
↳ | android.widget.TextView | |||
↳ | android.widget.EditText | |||
↳ | android.widget.AutoCompleteTextView |
![]()
An editable text view that shows completion suggestions automatically while the user is typing. The list of suggestions is displayed in a drop down menu from which the user can choose an item to replace the content of the edit box with.
简单的讲一个类似百度,google等输入搜索字串时自动提示的功能:
常用方法总结
下面是一个官方的示例:
To create a text entry widget that provides auto-complete suggestions, use the In this tutorial, you will create a
【1】Create an XML file named
list_item.xml and save it inside the res/layout/ folder. Edit the file to look like this:
This file defines a simple TextView that will be used for each item that appears in the list of suggestions.
这个文件定义了一个简单的TextView,用来即时显示自动匹配的选项
【2】Open the
res/layout/main.xml file and insert the following:
The TextView is a label that introduces the AutoCompleteTextView widget.
【3】Open
HelloAutoComplete.java and insert the following code for the onCreate() method:
After the content view is set to the main.xml layout, the AutoCompleteTextView widget is captured from the layout with findViewById(int) . A new ArrayAdapter is then initialized to bind the list_item.xml layout to each list item in the COUNTRIES string array (defined in the next step). Finally, setAdapter() is called to associate the ArrayAdapter with theAutoCompleteTextView widget so that the string array will populate the list of suggestions.
这里new了一个ArrayAdapter用来作为adapter.
【4】Inside the
HelloAutoComplete class, add the string array:
This is the list of suggestions that will be provided in a drop-down list when the user types into the AutoCompleteTextView widget.
【5】Run the application.
![]() |
More Information
Note that using a hard-coded string array is not a recommended design practice because your application code should focus on behavior, not content. Application content such as strings should be externalized from the code in order to make modifications to the content easier and facilitate localization of the content. The hard-coded strings are used in this tutorial only to make it simple and focus on the AutoCompleteTextView
widget. Instead, your application should declare such string arrays in an XML file. This can be done with a <string-array<
resource in your project res/values/strings.xml
file. For example:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="countries_array">
<item>Bahrain</item>
<item>Bangladesh</item>
<item>Barbados</item>
<item>Belarus</item>
<item>Belgium</item>
<item>Belize</item>
<item>Benin</item>
</string-array>
</resources>
ArrayAdapter
, replace the original ArrayAdapter
constructor line with the following:
String[] countries = getResources().getStringArray(R.array.countries_array);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, countries);