一、创建AutoCompleteTextView
1.在布局文件中声明一个AutoCompleteTextView:
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="text" /> <AutoCompleteTextView android:id="@+id/actv" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="5dp"/>
2.定义提示条目的样式,创建布局文件:
<TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" android:textSize="16sp" android:textColor="#000"> </TextView>
3.创建一个ArrayAdapter,用来提供数据:
autoCompleteTextView = (AutoCompleteTextView)findViewById(R.id.actv); List<String> list = new ArrayList<String>(); list.add("allotory"); list.add("bauble"); list.add("baobo"); list.add("album"); list.add("alow"); list.add("array");
4.为AutoCompleteTextView设置数据
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,R.layout.item ,list); autoCompleteTextView.setAdapter(arrayAdapter);
完整代码:
Main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="5dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="text" /> <AutoCompleteTextView android:id="@+id/actv" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="5dp"/> </LinearLayout>
Item.xml
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" android:textSize="16sp" android:textColor="#000"> </TextView>
AutoCompleteTextViewActivity.java
package com.android.activity; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; public class AutoCompleteTextViewActivity extends Activity { private AutoCompleteTextView autoCompleteTextView = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); autoCompleteTextView = (AutoCompleteTextView)findViewById(R.id.actv); List<String> list = new ArrayList<String>(); list.add("allotory"); list.add("bauble"); list.add("baobo"); list.add("album"); list.add("alow"); list.add("array"); ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,R.layout.item ,list); autoCompleteTextView.setAdapter(arrayAdapter); } }
运行结果: