首页 > 系统 > Android > 正文

Android开发高级组件之自动完成文本框(AutoCompleteTextView)用法示例【附源码下载】

2019-10-22 18:17:51
字体:
来源:转载
供稿:网友

本文实例讲述了Android开发高级组件之自动完成文本框(AutoCompleteTextView)用法。分享给大家供大家参考,具体如下:

通常来说自动完成文本框(AutoCompleteTextView)从EditText派生而出,实际上他也是一个编辑框,但他比普通的编辑框多了一个功能:当用户输入一定字符后,自动完成文本框会显示一个下拉菜单,供用户从中选择,当用户选择了某个菜单项过后,AutoCompleteTextView就会按用户选择自动填写该文本框。

自动完成文本框(AutoCompleteTextView),用于实现允许用户输入一定字符后,显示一个下拉菜单,供用户从中选择,当用户选择某个选项之后,按用户选择自动填写该文本框。

语法格式:

<AutoCompleteTextView属性列表></AutoCompleteTextView>

AutoCompleteTextView组件继承EditText,所以它支持EditText组件提供的属性,同时,该组件还有以下属性:

 

属性 功能
android:completionHint 下拉列表下面的说明性文字
android:completionThreshold 弹出下来列表的最小字符个数
android:dropDownAnchor 下拉列表的锚点或挂载点
android:dropDownHeight 下拉列表高度
android:dropDownWidth 下拉列表宽度
android:dropDownHorizontalOffset 下拉列表距离左边的距离
android:dropDownVerticalOffset 下拉列表距离上边的距离
android:dropDownSelector 下拉列表被选中的行的背景
android:popupBackground 下拉列表的背景

 

效果如下所示:

Android,高级组件,自动完成文本框,AutoCompleteTextView

具体实现步骤:

界面布局 res/layout/main.xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  android:layout_width="fill_parent"  android:layout_height="fill_parent"  android:orientation="horizontal"  android:background="#000000"><AutoCompleteTextView  android:layout_height="wrap_content"  android:text=""  android:id="@+id/autoCompleteTextView1"  android:completionThreshold="2"  android:completionHint="请输入内容"  android:background="#333333"   android:layout_marginLeft="10dp"  android:layout_weight="7"  android:layout_width="wrap_content"  ></AutoCompleteTextView><Button android:text="搜索"    android:id="@+id/button0"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_weight="1"    android:layout_marginLeft="10dp"/></LinearLayout>

MainActivity.java文件中:

首先设置保存下拉菜单列表项内容:

//此字符串是要在下拉菜单中显示的列表项private static final String[] COUNTRIES=new String[]{"jb51","jb51VEVB武林网","jb51脚本下载","jb51软件下载","www.vevb.com","VEVB武林网"};

onCreate()方法中获取自动完成文本框,并为自动完成文本框设置适配器,具体实现代码如下:

//获取自动完成文本框final AutoCompleteTextView textView=(AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1);//注意ArrayAdapter与SimpleAdapter的区别//创建一个ArrayAdapter适配器ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,COUNTRIES);textView.setAdapter(adapter);//为自动完成文本框设置适配器

最后为搜索按钮添加事件监听器:

//为搜索按钮添加事件监听器button.setOnClickListener(new OnClickListener() {  public void onClick(View arg0) {    Toast.makeText(MainActivity.this, textView.getText().toString(),Toast.LENGTH_SHORT).show();  }});

附:完整实例代码点击此处本站下载

希望本文所述对大家Android程序设计有所帮助。


注:相关教程知识阅读请移步到Android开发频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表