xml文件代码如下:
1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout
3 xmlns:android="http://schemas.android.com/apk/res/android"
4 android:orientation="vertical"
5 android:layout_width="fill_parent"
6 android:layout_height="fill_parent">
7
8 <AutoCompleteTextView
9 android:id="@+id/myAutoCompleteTextView"
10 android:layout_width="fill_parent"
11 android:layout_height="wrap_content" />
12
13 </LinearLayout>
java文件代码如下:
1 package com.example.sample_5_1;
2
3 import android.support.v7.app.AppCompatActivity;
4 import android.os.Bundle;
5 import android.widget.ArrayAdapter;
6 import android.widget.AutoCompleteTextView;
7
8 public class AutoCompleteActivity extends AppCompatActivity {
9 private static final String[] myStr = new String[]{
10 "vae","victory","vision","virtue","vital"
11 };
12 @Override
13 protected void onCreate(Bundle savedInstanceState) {
14 super.onCreate(savedInstanceState);
15 setContentView(R.layout.activity_auto_complete);
16 ArrayAdapter<String> aa = new ArrayAdapter<String>( //创建适配器
17 this, // Context
18 android.R.layout.simple_dropdown_item_1line,
19 //使用Android自带的简单布局
20 myStr); //资源数组
21 AutoCompleteTextView myAutoCompleteTextView =
22 (AutoCompleteTextView) findViewById(R.id.myAutoCompleteTextView);
23 //得到控件的引用
24 myAutoCompleteTextView.setAdapter(aa); //设置适配器
25 myAutoCompleteTextView.setThreshold(1); //定义需要用户输入的字符数
26 }
27 }
效果图如下:(输入一个V会自动提示以V开头的所有内容)