在Android中用AutoCompleteTextView实现在输入框中输入我们想要输入的信息就会出现其他与其相关的提示信息。
AutoCompleteTextView是一个可编辑的文本视图显示自动完成建议当用户键入。建议列表显示在一个下拉单户 可以从中选择一项,以完成输入。建议列表是从一个数据适配器获取的数据。它有三个重要的方法clearListSelection():清除选中的列表项、dismissDropDown():如果存在关闭下拉菜单、getAdapter():获取适器。
以下图所示的内容来实现AutoCompleteTextView布局:
activity_autocomplete_textview_layout.xml布局如下:
<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<AutoCompleteTextView
android:id="@+id/autocomplete_txt"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout></span>
AutoCompleteTextViewActivity.java代码如下:
<span style="font-size:18px;">package com.sc.android.ui.autocompletetextview;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import com.sc.android.R;
public class AutoCompleteTextViewActivity extends Activity {
private AutoCompleteTextView mAutoCompleteTxt;
private String[] arrays = { "January", "February", "March", "April", "May",
"June", "July", "August", "September", "October", "November",
"December" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_autocomplete_textview_layout);
mAutoCompleteTxt = (AutoCompleteTextView) findViewById(R.id.autocomplete_txt);
mAutoCompleteTxt.setThreshold(1);
mAutoCompleteTxt.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
String str = s.toString();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
AutoCompleteTextViewActivity.this,
android.R.layout.simple_expandable_list_item_1, arrays);
mAutoCompleteTxt.setAdapter(adapter);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
}
</span>
上面的View布局直接调用的系统xml布局,没有去自定义布局,对于简单的文本布局用系统的布局要方便点。当然系统的布局格式固定的不是很好看,所以又需求的可以使用自定义的布局。
注:xml布局中AutoCompleteTextView显示的宽度android:layout_width="match_parent"如果设置的不够,其中的内容将不会显示出来,所以设置的时候要小心。