android AutoCompleteTextView 使用示例

创建布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <!-- 定义一个自动完成文本框,指定输入一个字符后进行提示 -->
    <AutoCompleteTextView
        android:id="@+id/autoCompleteText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:completionHint="Please Select:"
        android:dropDownHorizontalOffset="10dp"
        android:completionThreshold="1"
        />

    <MultiAutoCompleteTextView
        android:id="@+id/multiAutoCompleteText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:completionThreshold="1"
        />

</LinearLayout>

对应的Activity文件代码如下:

package com.toby.personal.testlistview;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.MultiAutoCompleteTextView;

public class MainActivity extends Activity {

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

        String[] array1 = new String[]{"C", "C++", "Cpp", "Qt", "QML", "Java", "PHP", "Android"};

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

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

        if (autoCompleteText != null) {
            autoCompleteText.setAdapter(a);
        }

        MultiAutoCompleteTextView multiAutoCompleteText
                = (MultiAutoCompleteTextView) findViewById(R.id.multiAutoCompleteText);

        if (multiAutoCompleteText != null) {
            multiAutoCompleteText.setAdapter(a);
            multiAutoCompleteText.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
        }

    }
}

参考文献:《疯狂Android讲义(第2版)》

    原文作者:赵者也
    原文地址: https://www.jianshu.com/p/c92d37c830b9
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞