6.18实现AutoCompleteTextView
问题
您希望保存用户不要输入整个单词,而是根据用户输入的前几个字符自动填写条目。

使用AutoCompleteTextView小部件作为EditText和微调框之间的交叉,启用自动完成。
讨论
此布局包括支持自动完成的TextView。使用AutoTextCompleteTextView小部件完成自动完成。例6-25显示了布局XML代码。
实例6-25。自动完成布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/field"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<AutoCompleteTextView
android:id="@+id/autocomplete"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:completionThreshold="2"/>
</LinearLayout>

AutoCompleteTextView中的completionThreshold字段设置用户必须在TextView中输入的最小字符数,以便显示与其输入对应的自动完成选项。


Activity(我们实现自动完成)应该实现TextWatcher,这样我们可以覆盖onTextChanged()方法:


public class AutoComplete extends Activity implements TextWatcher {


我们需要重写未实现的方法:onTextChanged,


beforeTextChanged和afterTextChanged。我们还需要三个字段:


•TextView上的句柄


•AutoCompleteTextView上的句柄


•自动完成将选择的字符串项列表。


这三个项目如下所示:


private TextView field;
private AutoCompleteTextView autocomplete;
String autocompleteItems [] = {"apple", "banana", "mango", "pineapple","apricot",
"orange", "pear", "grapes"};


我们的onTextChanged()方法,如下所示,简单地将文本字段的当前值复制到另一个文本字段;这不是强制性的,但在本演示中,它将显示您在自动完成组件中设置的值。


@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
field.setText(autocomplete.getText());
}


在相同活动的onCreate方法中,我们获得了TextView上的句柄和布局的AutoCompleteTextView组件。对于AutoCompleteTextView,我们将设置一个String适配器:

setContentView(R.layout.main);
field = (TextView) findViewById(R.id.field);
autocomplete = (AutoCompleteTextView)findViewById(R.id.autocomplete);
autocomplete.addTextChangedListener(this);
autocomplete.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, autocompleteItems));