​ Android--自动搜索提示 ​

2015-01-24 22:09  ​​贺臣​​ 阅读(2229)  评论(1)  ​


编辑 收藏



 

一. 效果图

  在Google或者百度搜索的时候,在输入关键词都会出现自动搜索的提示内容,类似如下的效果,输入b 则出现包含b的相关词条

Android--自动搜索提示_Android

 

 

二. 布局代码


Android--自动搜索提示_Android_02Android--自动搜索提示_Android_03


<?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/autoText"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginTop="10dp"
/>

</LinearLayout>

AutoCompleteTextView布局代码

  以上是上面效果的布局代码,使用的是AutoCompleteTextView组件

 

三.设置数据源

  在这里使用AutoCompleteTextView同样需要到ArrayAdapter<T> 这个类


Android--自动搜索提示_Android_04Android--自动搜索提示_Android_05


public class PicActivity extends Activity {

private String[] items={
"ab",
"db",
"adg",
"dbee",
"adre",
"ayrtr",
"btee",
"bdw",
"bt45",
"aire",
"vfdr",
"434"
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pic);

AutoCompleteTextView autoText=(AutoCompleteTextView)findViewById(R.id.autoText);

ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, items);

autoText.setAdapter(adapter);
autoText.setThreshold(1);
}
}

数据源设置