您的位置:首页 > 移动开发 > Android开发

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

2018-01-02 15:18 961 查看

本文实例讲述了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 下拉列表的背景

效果如下所示:

具体实现步骤:

界面布局 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","jb51脚本之家",
"jb51脚本下载","jb51软件下载","www.jb51.net","脚本之家"};

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开发入门与进阶教程》、《Android调试技巧与常见问题解决方法汇总》、《Android基本组件用法总结》、《Android视图View技巧总结》、《Android布局layout技巧总结》及《Android控件用法总结

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

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐