Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 開發入門

Android 基礎教學(八):仿搜尋引擎的自動提示欄——AutoCompleteTextView 應用

編輯:開發入門

我們上網搜尋資料時幾乎都會用到百度或 Google,在輸入框打入一兩個字,對應的候選字串就會自動跳出來。這種效果在 Android 中該怎麼做?其實只要 AutoCompleteTextView 搭配 ArrayAdapter,就能做出類似 Google 搜尋提示的體驗。

實作原理

整體流程只有三步:

  1. 在版面配置中放一個 AutoCompleteTextView。
  2. 準備一組預先定義好的字串陣列,把它放進 ArrayAdapter。
  3. 呼叫 AutoCompleteTextView 的 setAdapter() 方法,自動提示的功能就完成了。

完成後,只要輸入 ab,凡是包含 ab 的字串都會被列出來成為候選。

效果預覽

AutoCompleteTextView 自動提示效果

版面配置 main.xml

<?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="試試輸入 ab"
    />
<AutoCompleteTextView
    android:id="@+id/actv"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:completionThreshold="2"
    />
</LinearLayout>

completionThreshold 屬性用來設定「至少輸入幾個字才開始提示」,預設值是 2。若你希望打第一個字就跳出候選,把它設為 1 即可。

主程式 AutoCompleteTextViewDemo.java

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 static final String[] autoStrs = new String[] {
        "abc", "abd", "abe", "bcd", "cde", "apple", "application"
    };

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

        // 透過 findViewById() 取得 actv
        AutoCompleteTextView actv =
                (AutoCompleteTextView)findViewById(R.id.actv);

        // 建立 ArrayAdapter 並把 autoStrs 字串陣列傳入 actv
        ArrayAdapter adapter = new ArrayAdapter(this,
                android.R.layout.simple_dropdown_item_1line, autoStrs);

        actv.setAdapter(adapter);
    }
}

這裡的版面樣式選用了 simple_dropdown_item_1line,也就是下拉候選列的外觀。程式的可注意的是:真正讓提示生效的,就是最後那一行 setAdapter。Adapter 負責把字串陣列攤平成一列出現的候選清單,AutoCompleteTextView 則負責比對輸入內容並控制顯示時機。

全部程式就這麼一點,效果卻很實用。實務上要留意兩點:一是候選資料若來自網路或資料庫,資料量大時應改用 CursorAdapter 並搭配非同步查詢,避免阻塞主執行緒造成畫面卡頓;二是若想改進比對邏輯(例如忽略大小寫順序、或做模糊比對),可以自訂 Adapter 覆寫 getFilter() 回傳自製的 Filter 物件。

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