activity_main.xml文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.autocompletetextviewdemo.MainActivity" >
<AutoCompleteTextView
android:id="@+id/autoCompleteTextView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入要搜索的关键字"
android:completionThreshold="2" >
<requestFocus />
</AutoCompleteTextView>
</LinearLayout>
MainActivity.java
package com.example.autocompletetextviewdemo;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
public class MainActivity extends ActionBarActivity {
//声明控件
AutoCompleteTextView actv;
String[] str={"beijing","beijing1","beijing2","nanjing","yanjing","yantai","nanguo"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
actv=(AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
//需要一个适配器
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, str);
//将适配器与控件绑定
actv.setAdapter(adapter);
}
}