安卓控件使用系列7:AutoCompleteTextView和MultiAutoCompleteTextView实现输入字符自动提醒

时间:2022-08-30 00:05:21

相信大家在百度上搜索一个信息的时候都看到过出现下面的几条信息提醒,然后点击提醒的信息,信息就会直接显示在文本控件上。那么我们在移动端如何实现这样的效果呢。下面我们来分享一下我们的实现方法。

整体思路:首先定义一个字符串数组,把这个字符串数组设置在适配器上,再把适配器绑定到AutoCompleteTextView控件上,这样就实现了输入一些字符,自动弹出与前几个字符相同的提示信息;把这个适配器绑定到MultiAutoCompleteTextView控件上,实现的就是以逗号为分隔符输入的字符持续出现提示信息的功能。

activity_main.xml文件:

<LinearLayout 
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<TextView
android:id="@+id/autotextview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="AutoCompleteTextView"
/>
<AutoCompleteTextView
android:id="@+id/autotext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>

<TextView
android:id="@+id/multextview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="MultiAutoCompleteTextView"
/>
<MultiAutoCompleteTextView
android:id="@+id/multext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>

MainActivity.java文件:

private AutoCompleteTextView auto;
private MultiAutoCompleteTextView mul;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
auto=(AutoCompleteTextView)findViewById(R.id.autotext);
String[] autoStrings=new String[]{"明星霍建华","明星周渝民","明星黄渤","帅哥谢霆锋","黄金组合羽泉","亚洲舞王罗志祥","音乐怪才周杰伦"};
//第二个参数表示适配器的下拉风格
ArrayAdapter<String> adapter=new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_dropdown_item_1line,autoStrings);
auto.setAdapter(adapter);
//可以以逗号为分隔符连续提示信息
mul=(MultiAutoCompleteTextView)findViewById(R.id.multext);
mul.setAdapter(adapter);
mul.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());

}