【Android 开发教程】AutoCompleteTextView

本文介绍如何使用Android的AutoCompleteTextView来实现自动补全功能。通过一个具体的例子展示了如何设置和使用AutoCompleteTextView,包括定义布局文件、初始化数据源及配置组件属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本章节翻译自《Beginning-Android-4-Application-Development》,如有翻译不当的地方,敬请指出。

原书购买地址http://www.amazon.com/Beginning-Android-4-Application-Development/dp/1118199545/


AutoCompleteTextView和EditText很相似,事实上,AutoCompleteTextView就是EditText的子类。使用AutoCompleteTextView,当用户正在输入时,会自动弹出一些提示信息。下面的例子将会展示如何使用AutoCompleteTextView去自动地帮助用户完成输入。

1。 创建一个工程:BasicViews3。

2。 main.xml中的代码。

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7. <TextView  
  8.     android:layout_width="fill_parent"  
  9.     android:layout_height="wrap_content"  
  10.     android:text="Name of President" />  
  11.   
  12. <AutoCompleteTextView android:id="@+id/txtCountries"  
  13.     android:layout_width="fill_parent"  
  14.     android:layout_height="wrap_content" />  
  15.   
  16. </LinearLayout>  
3、BasicViews3Activity.java中的代码。
[java] view plain copy
  1. public class BasicViews3Activity extends Activity {  
  2.     String[] presidents = {  
  3.             "Dwight D. Eisenhower",  
  4.             "John F. Kennedy",  
  5.             "Lyndon B. Johnson",  
  6.             "Richard Nixon",  
  7.             "Gerald Ford",  
  8.             "Jimmy Carter",  
  9.             "Ronald Reagan",  
  10.             "George H. W. Bush",  
  11.             "Bill Clinton",  
  12.             "George W. Bush",  
  13.             "Barack Obama"  
  14.         };  
  15.   
  16.     /** Called when the activity is first created. */  
  17.     @Override  
  18.     public void onCreate(Bundle savedInstanceState) {  
  19.         super.onCreate(savedInstanceState);  
  20.         setContentView(R.layout.main);  
  21.           
  22.         ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,  
  23.             android.R.layout.simple_dropdown_item_1line, presidents);  
  24.   
  25.         AutoCompleteTextView textView = (AutoCompleteTextView)  
  26.             findViewById(R.id.txtCountries);  
  27.   
  28.         textView.setThreshold(3);  
  29.         textView.setAdapter(adapter);  
  30.     }  
  31. }  
4、F11调试。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值