这篇文章主要为大家展示了“Android中自动完成文本框AutoCompleteTextView怎么用”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“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中自动完成文本框AutoCompleteTextView怎么用”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。