編輯:開發入門
我們上網搜尋資料時幾乎都會用到百度或 Google,在輸入框打入一兩個字,對應的候選字串就會自動跳出來。這種效果在 Android 中該怎麼做?其實只要 AutoCompleteTextView 搭配 ArrayAdapter,就能做出類似 Google 搜尋提示的體驗。
整體流程只有三步:
完成後,只要輸入 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="試試輸入 ab"
/>
<AutoCompleteTextView
android:id="@+id/actv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:completionThreshold="2"
/>
</LinearLayout>
completionThreshold 屬性用來設定「至少輸入幾個字才開始提示」,預設值是 2。若你希望打第一個字就跳出候選,把它設為 1 即可。
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 物件。
Android 感測器開發指南:從方向與加速度到環境監控
讓 Android 成為感測與監控平台 Android 不只是手機作業系統,也是一個能接觸硬體感測資料的開發平台。對 Java 開發者而言,只要透過 Android SD
用 Eclipse 開發 Android 應用程式(四):內容提供者與 Google Maps 實戰
打造內容提供者與 Google Maps 應用程式 你已經看過一個完整的應用程式範例,現在簡單談談更複雜的一款應用。 內容提供者與 Google Maps 本教學討論的第
Android 自訂對話框:HelpDialog 與 ScrollView 排版
自訂對話框的需求 Android 的 AlertDialog 可以承載自訂版面,讓提示框不只是純文字,而能包含說明、圖示、版本資訊或可捲動內容。對於需要較長說明或較完整資
用 Eclipse 與 Android 元件做開發(四):用 ListView 與 ContentProvider 做通訊錄
用 ListView 元件:一個簡單的範例應用 這一節我們要動手做一個範例應用,用 ListView 元件把電話簿裡的所有聯絡人列出來(見圖 9a、9b)。這個例子不只示