Android开发:AutoCompleteTextView的使用举例


代码如下:

AppMain.java

  1. package lxy.litsoft;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import Android.app.Activity;  
  7. import android.os.Bundle;  
  8. import android.widget.ArrayAdapter;  
  9. import android.widget.AutoCompleteTextView;  
  10.   
  11. public class AppMain extends Activity {  
  12.       
  13.     AutoCompleteTextView autoCompleteTextView;  
  14.     List<String> list;  
  15.     ArrayAdapter<String> arrayAdapter;  
  16.       
  17.     public void onCreate(Bundle savedInstanceState) {  
  18.         super.onCreate(savedInstanceState);  
  19.         setContentView(R.layout.main);  
  20.           
  21.         //实例化AutoCompleteTextView对象   
  22.         autoCompleteTextView = (AutoCompleteTextView)findViewById(R.id.autoComplete);  
  23.         //实例化List对象并添加item   
  24.         list = new ArrayList<String>();  
  25.         list.add("liu_zhen_wei");  
  26.         list.add("liu_zhen_wei_01");  
  27.         list.add("liu_zhen_wei_02");  
  28.         list.add("wang1");  
  29.         list.add("wang2");  
  30.         list.add("huohuo");  
  31.         //实例化ArrayAdapter对象为AutoCompleteTextView提供数据   
  32.         arrayAdapter = new ArrayAdapter<String>(this,R.layout.item,list);  
  33.         //为AutoCompleteTextView添加适配器   
  34.         autoCompleteTextView.setAdapter(arrayAdapter);  
  35.     }  
  36. }  
main.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     >  
  7. <AutoCompleteTextView  
  8.     android:id="@+id/autoComplete"  
  9.     android:layout_marginTop="100dip"  
  10.     android:layout_marginLeft="30dip"  
  11.     android:layout_marginRight="30dip"  
  12.     android:layout_width="fill_parent"   
  13.     android:layout_height="wrap_content" ></AutoCompleteTextView>  
  14. </LinearLayout>  
item.mxl
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <TextView    
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     android:layout_width="fill_parent"   
  5.     android:layout_height="fill_parent"   
  6.     />  
创建一个AutoCompleteTextView的步骤
1.在布局文件中声明一个AutoCompleteTextView
2.在res/layout文件夹下新建一个布局文件,名为list_item.xml确定AutoComleteTextView的提示样式
3.创建一个ArrayAdapter为AutoCompleteTextView提供数据
List<String> list = new ArrayList<String>();
list.add("abcd");
list.add("abdd");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
    this,R.layout.item,list);
4.为AutoCompleteTextView添加适配器

autoCompleteTextView.setAdapter(array Adapter);


相关内容