一次输入内容自动完成文本框(AutoCompleteTextView)
一次输入内容自动完成文本框(AutoCompleteTextView)
AutoCompleteTextView和EditText组件类似,都可以输入文本。
但AutoCompleteTextView组件可以和一个字符串数组或List对象
绑定,当用户输入两个及以上字符时,系统将在
AutoCompleteTextView组件下方列出字符串数组中所有以输入
字符开头的字符串,这一点和www.google.com的搜索框非常相似,
当输入某一个要查找的字符串时,google搜索框就会列出以这个
字符串开头的最热门的搜索字符串列表。
|
1、布局: <RelativeLayout 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=".MainActivity" >
<AutoCompleteTextView
android:id="@+id/autoCompleteTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:completionThreshold="1"
>
<requestFocus />
</AutoCompleteTextView>
</RelativeLayout>
|
2、核心代码: package cn.zengfansheng.autocompletetextview;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
public class MainActivity extends Activity {
private AutoCompleteTextView actv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actv = (AutoCompleteTextView) this.findViewById(R.id.autoCompleteTextView);
String[] names = { "老张", "老方", "老毕", "李明", "李丽", "陈江", "abc", "acc" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getApplicationContext(),android.R.layout.simple_spinner_dropdown_item, names);
actv.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
} |
3、结果: |