2.9 自动完成文本框

时间:2021-04-02 22:44:20

一、布局文件

1、Activity.xml 添加如下代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.yuancan.test101001.MainActivity">


<AutoCompleteTextView
android:id="@+id/atv_content"
android:layout_width="match_parent"
android:layout_height="48dp"
android:completionHint="请输入搜索内容"
android:completionThreshold="1"
/>


<MultiAutoCompleteTextView
android:id="@+id/matv_content"
android:layout_width="match_parent"
android:layout_height="48dp"
android:completionThreshold="1"
/>


</LinearLayout>

二、Java代码

1、MainActivity.java 中添加如下代码:

package com.example.yuancan.test101001;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.MultiAutoCompleteTextView;

public class MainActivity extends AppCompatActivity {

private AutoCompleteTextView atv_content;
private MultiAutoCompleteTextView matv_content;

private static final String[] data = new String []{"小猪猪","小狗狗","小鸡鸡","小猫猫","小咪咪"};

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

atv_content = (AutoCompleteTextView)findViewById(R.id.atv_content);
matv_content = (MultiAutoCompleteTextView)findViewById(R.id.matv_content);

ArrayAdapter adapter = new ArrayAdapter(MainActivity.this,android.R.layout.simple_dropdown_item_1line,data);
atv_content.setAdapter(adapter);

ArrayAdapter adapter1 = new ArrayAdapter(getApplicationContext(),android.R.layout.simple_dropdown_item_1line,data);
matv_content.setAdapter(adapter1);
//设置分隔符
matv_content.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
}
}

AutoCompleteTextView 和 MultiAutoCompleteTextView 作用差不多。