一、基础知识:
搜索引擎:在我们搜索框中输入文本的时候,文本框会自动弹出下拉菜单提示,自动匹配用户输入的内容。
实现这个功能,需要一个组件AutoCompleteTextView,它是一个文本框控件,继承自TextView。与TextView不同的是,当用户在文本框中输入文本的时候,文本框会自动弹出一个列表框方便用户选择。当用户点下列表框中的选项是,该条选项会代替文本框中的原有内容。当用户按返回键或者Enter键时,下拉列表框会自动消失。
下拉列表框中的内容是从一个数据Adaptor中获取的,并且只有在用户输入规定的字符后才会开始显示,可以在xml文件中声明,即android:completionThreshold="1",表示在用户输入一个字符的时候开始出现下拉列表提示。
二、方案代码:
1. "....\src\com\example\MainActivity.java"
package com.example.wenbenzidong;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
public class MainActivity extends Activity {
//定义字符串数组,作为提示的文本
String[] books = new String[]{
"sunyanzi-hey jude",
"sunyanzi-the moment",
"sunyanzi-tonight I feel close to you",
"sunyanzi-leave me alone"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//创建一个ArrayAdapter,封装数组
ArrayAdapter<String> aa = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
books);
AutoCompleteTextView actv = (AutoCompleteTextView)
findViewById(R.id.AutoCompleteTextView01);
//设置Adapter
actv.setAdapter(aa);
}
}
2. ".... \res\layout\activity_main.xml "
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
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" >
<TextView
android:id="@+id/TextView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/wenben" />
<AutoCompleteTextView
android:text=""
android:id="@+id/AutoCompleteTextView01"
android:layout_width="fill_parent"
android:layout_height="50dip"
android:dropDownHorizontalOffset="20dp"
android:completionHint="请选择您最喜欢的歌曲"
android:completionThreshold="1"
></AutoCompleteTextView>
</LinearLayout>
3. ".... \res\values\string.xml "
在res/layout文件夹下新建一个xml文件,文件名为list_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:background="#ffffff"
android:padding="10dp"
android:textSize="16sp"
android:textColor="#000000">
</TextView><span style="font-family:Arial;color:#ff0000;"><span style="font-size: 14px; line-height: 26px;"><strong>
</strong></span></span>
三、效果展示: