Android 之 自动匹配字符AutoCompleteTextView

 

AutoCompleteTextView是自动匹配字符,当我们输入一个单词或一段话的前几个字时,就会自动为你匹配后面的内容看效果图:

下面是代码:

MainActivit:

package com.example.autocompletetextview;

import java.util.ArrayList;
import java.util.List;

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

public class MainActivity extends ActionBarActivity {

    AutoCompleteTextView autoCompleteTextView = null;
    AutoCompleteTextView auto2 = null;
    private static final String[] COUNTRIES = {"china","canada","Belgium", "France", "Italy", "Germany", "Spain"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.auto1);
        auto2 = (AutoCompleteTextView) findViewById(R.id.auto2);
        
        /*静态方式,自动匹配的值已经提前设置好了
         * 第一个参数是指当前上下文
         * 第二个参数是显示的匹配布局,此处用的是Android已有的布局
         * 第三个参数是存储自动匹配的值的数组
         */
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,COUNTRIES);
        autoCompleteTextView.setAdapter(adapter);
        
        /*
         * 动态方式,自动匹配的值由list决定
         */
        List<String> list = new ArrayList<String>();
        list.add("测试aadd");
        list.add("测试object");
        list.add("测试home");
        ArrayAdapter<String>  adapter2 = new ArrayAdapter<String>(this, R.layout.simple_1, list);
        auto2.setAdapter(adapter2);
    }
}

main_activity:

<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" >

    
    <TextView 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="静态实现:"/>
    <AutoCompleteTextView 
        android:id="@+id/auto1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <TextView 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="动态实现:"/>
    <AutoCompleteTextView 
        android:id="@+id/auto2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

simple_1.xml:

<?xml version="1.0" encoding="utf-8"?>
    <TextView 
        android:id="@+id/textview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:textSize="20dp"
        xmlns:android="http://schemas.android.com/apk/res/android"/>

 

posted @ 2015-11-01 16:56  千个太阳在手中  阅读(1127)  评论(0编辑  收藏  举报