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

Android AutoCompleteTextView 自動完成控件的基本用法

編輯:關於 Android 程式設計

當我們在搜索框裡輸入部分內容時,如果能即時給出匹配的建議列表,用戶體驗會大大提升——這正是 AutoCompleteTextView 的用武之地,很多搜索場景(如百度搜索提示)都離不開它。本文用四個步驟帶大家實現這個效果。

一、在佈局中聲明控件

<AutoCompleteTextView
    android:id="@+id/autocomplete_country"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="5dp" />

二、定義提示項的樣式

在 layout 目錄下新建一個 list_item.xml,用來指定下拉提示中每一項的外觀:

<TextView xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="16sp"
    android:textColor="#000">
</TextView>

三、用 ArrayAdapter 提供數據

AutoCompleteTextView 需要一個 ArrayAdapter 來提供建議數據。它會把數組中的內容與用戶輸入進行匹配,並以下拉列表的形式展示出來:

public void setAutoCompleteTextView() {
    autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autocomplete_country);
    // COUNTRIES 是一個字符串數組
    // R.layout.list_item 指定提示項的樣式
    ArrayAdapter<String> arrayAdapter =
        new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES);
    autoCompleteTextView.setAdapter(arrayAdapter);
}

四、關聯控件與適配器

通過 setAdapter 把 AutoCompleteTextView 和 ArrayAdapter 關聯起來後,控件便具備了自動完成的能力。用戶每輸入一個字符,它就會實時篩選出匹配的候選項供選擇。

可以看到,AutoCompleteTextView 的實現非常輕量:一個佈局、一個樣式、一個數據適配器即可。如果想自定義更複雜的匹配規則,也可以繼承 BaseAdapter 自行實現,自由度會更高。

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