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

AutoCompleteTextView 實作教學:打造搜尋自動完成效果

編輯:初階開發

我們幾乎每天都會用百度或 Google 搜尋,輸入框裡才打兩個字,候選詞就自動跳出來。這種效果在 Android 上要怎麼做?其實只要把 AutoCompleteTextView 這個 Widget 搭配 ArrayAdapter,就能做出類似的提示體驗。

實作原理

三步即可完成:先在 Layout 中放一個 AutoCompleteTextView;接著準備一組字串陣列;最後透過 setAdapter 把 ArrayAdapter 掛上去。掛好之後,只要輸入 ab,所有含 ab 的字串就會自動列入候選。

版面配置 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="Please input:"
        />
    <AutoCompleteTextView
        android:id="@+id/actv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />
</LinearLayout>

主程式 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 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);

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

        // 建立 ArrayAdapter 並把 autoStrs 字串陣列帶入
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, autoStrs);
        actv.setAdapter(adapter);
    }
}

幾個實務上的延伸

這個範例的資料是寫死在程式裡的,實務上更常見的是把 adapter 換成自訂的 CursorAdapter 或繼承 BaseAdapter 的實作,資料來源改為資料庫或網路 API,並自行覆寫 getFilter 控制比對邏輯。另外可搭配 setThreshold(1) 調整觸發提示所需的最小字元數,或實作 OnItemClickListener 處理使用者選中候選後的後續動作。

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