<AutocompleteTextView>:自动生成视图标签
<MultiAutoCompleteTextView>:可以实现多次匹配
android:completionThreshold="1":指定输入多少个字符开始匹配,默认值为:2
(1)在res资源文件中的values子文件中添加所需的xml文件
代码如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<String-array name = "country_array">
<item>Afghanistan</item>
<item>Albania</item>
<item>Alqeria</item>
<item>American</item>
<item>Andorra</item>
<item>Angola</item>
<item>Anguilla</item>
<item>Antarctica</item>
</String-array>
</resources>
(2)在activity_main.xml文件使用<AutocompleteTextView>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--android:completionThreshold="1":将从输入第一个进行搜素匹配
<AutoCompleteTextView>:自动生成视图-->
<AutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/autoCompleteTextView"
android:completionThreshold="2"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
/>
</RelativeLayout>
(3)在java文件中写业务逻辑
package com.example.lenovo.autocompletetextview;
import android.content.res.Resources;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
private AutoCompleteTextView autoCompleteTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.autoCompleteTextView = (AutoCompleteTextView) this.findViewById(R.id.autoCompleteTextView);
//1.得到资源对象
Resources resources = this.getResources();
//2.读取指定资源的数组
String[] country = resources.getStringArray(R.array.country_array);
System.out.println("country="+ Arrays.toString(country));
//3.实例化数组适配器对象
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,//系统提供好的布局文件,即TextView控件
country//数据源
);
//4.设置当前控件的适配器对象adapter
this.autoCompleteTextView.setAdapter(adapter);
}
}