Day4.2--Android高级UI控件之AutoCompleteTextView的使用

来源:互联网 发布:仿163k地方门户 源码 编辑:程序博客网 时间:2024/05/21 11:26

AutoCompleteTextView--自动不全文本视图, 先来看下它的继承关系:

java.lang.Object   ↳android.view.View    ↳android.widget.TextView     ↳android.widget.EditText      ↳android.widget.AutoCompleteTextView可以看到,AutoCompleteTextView实际上是继承自EditText的, 因此它也是一个可编辑的文本框

那么它也EditText得区别在哪里呢, 看下动态图所示:


从图中可以看出,当用户输入相应数量的字符内容之后,会在文本框下方弹出一个提示的列表视图,其中提示内容是以输入字符开头的。这也就是它和EditText的区别所在


接下来看一下如何在代码中使用AutoCompleteTextView。

首先在xml布局文件中,通过<AutoCompleteTextView>标签添加视图,如下代码所示:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <!--     1、AutoCompleteTextView继承自EditText,    因此EditText具有的属性AutoCompleteTextView都可以使用    2、android:completionThreshold指定输入多少字符开始进行模糊搜索     -->    <AutoCompleteTextView         android:id="@+id/autoCompleteTextView"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:completionThreshold="1"        android:hint="请输入单词:"/></LinearLayout>

注意:android:completionThreshold属性默认值是2,也就是默认需要输入2个字符时,才会弹出提示框信息

接下来,看MainActivity.java中的代码, 如下所示:

// 1、初始化AutoCompleteTextView控件AutoCompleteTextView autoText = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);// 2、初始化数据源String[] data = new String[]{"abc", "abcdef", "asd", "bdef"};// 3、初始化适配器ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, data);autoText.setAdapter(adapter);

这样就将一个数组中的数据绑定到一个AutoCompleteTextView当中,假如在文本框中输入a,则会弹出abc、abcdef、asd三个item提示。

注意:AutoCompleteTextView弹出的信息,并不是模糊搜索之后的结果,而是以输入内容为开头作为依据进行查询


AutoCompleteTextView可以通过以下方式,设置弹出list的点击事件:

autoText.setOnItemClickListener(new OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view, int position, long id) {TextView textView = (TextView) view;Toast.makeText(MainActivity.this, textView.getText(), Toast.LENGTH_SHORT).show();}});



1 0
原创粉丝点击