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

AutoCompleteTextView 自動補全輸入框實作教學

編輯:關於 Android 程式設計

我們幾乎每天都在用百度或 Google 搜索:鍵入一兩個字,候選詞就自動跳出來。這種效果在 Android 裡並不需要自己寫過濾算法——AutoCompleteTextView 搭配 ArrayAdapter 就能完成。

實作原理

三步即可:在佈局中放置 AutoCompleteTextView;準備一個字符串數組並交給 ArrayAdapter;最後呼叫 setAdapter。之後只要輸入 ab,所有包含 ab 的字符串就會自動列入候選。

一、佈局文件

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Please input:" />

    <AutoCompleteTextView
        android:id="@+id/actv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

二、控制層程式碼

package com.android.test;

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

public class AutoCompleteTextViewDemo extends Activity {
    private AutoCompleteTextView actv;
    private static final String[] autoStrs = new String[]{"a", "abc", "abcd", "abcde", "ba"};

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // 取得 actv 控件
        actv = (AutoCompleteTextView) findViewById(R.id.actv);

        // 建立 ArrayAdapter,把字符串數組傳入
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                this, android.R.layout.simple_dropdown_item_1line, autoStrs);
        actv.setAdapter(adapter);
    }
}

就這幾行,自動補全已經生效。

實務上的兩個調整點

預設的匹配規則是「前綴匹配」,若希望像搜索引擎那樣做包含匹配,可以自定義 Adapter 並覆寫 getFilter;另外下拉列表的樣式由 android.R.layout.simple_dropdown_item_1line 決定,替換成自定義 layout 即可改成帶圖標的候選項。若還想讓使用者必須從候選中選擇,記得在 setOnItemClickListener 裡把選中值寫回輸入框。

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