Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自動完成輸入框 AutoCompleteTextView 使用教學

編輯:關於 Android 開發

輸入前幾個字就自動補全

AutoCompleteTextView 能在使用者輸入單詞或句子的前幾個字時,自動彈出匹配的候選內容,大幅減少輸入。效果如下:

一、MainActivity

它支持靜態與動態兩種數據來源。靜態方式使用預先寫好的陣列,動態方式則由 List 決定:

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);

        // 靜態方式:自動匹配值已提前設置好
        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);
    }
}

二、activity_main.xml

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://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="https://schemas.android.com/apk/res/android" />

核心就是為 AutoCompleteTextView 設置一個 ArrayAdapter。無論資料來自靜態陣列還是動態 List,只要綁定好適配器,就能實現輸入即補全的效果。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved