布局文件:
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/title" /> <AutoCompleteTextView
android:id="@+id/actv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/title"/>
Activity代码:
package cn.luxh.autocomplete; import android.os.Bundle;
import android.app.Activity;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView; public class MainActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); AutoCompleteTextView actv = (AutoCompleteTextView) findViewById(R.id.actv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,getData());
//设置适配器
actv.setAdapter(adapter);
//输入一个字符开始提示
actv.setThreshold(1);
} /**
* 模拟数据
* @return
*/
private String[] getData(){
String[] names = {
"Dwight D. Eisenhower",
"John F. Kennedy",
"Lyndon B. Johnson",
"Richard Nixon",
"Gerald Ford",
"Jimmy Carter",
"Ronald Reagan",
"George H. W. Bush",
"Bill Clinton",
"George W. Bush",
"Barack Obama"};
return names;
} }
运行效果: