Android 系列 6.18实现AutoCompleteTextView

117 篇文章 4 订阅
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));


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值