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

Android 入門教程(十二):用 AutoCompleteTextView 做搜尋自動提示

編輯:Android 開發實例

我們上網幾乎都會用搜尋引擎,輸入一兩個字之後,對應的關鍵字就會自動跳出來。這種效果在 Android 裡怎麼做?其實只要 AutoCompleteTextView 搭配 ArrayAdapter,就能做出類似搜尋建議的互動。

[效果圖]

實作步驟

流程只有三步:在版面中放一個 AutoCompleteTextView,把預先準備好的字串陣列交給 ArrayAdapter,最後用 setAdapter() 掛上去。完成後,只要輸入 ab,清單裡所有含 ab 的項目就會自動浮現。

版面檔 main.xml

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

    <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);

        actv = (AutoCompleteTextView) findViewById(R.id.actv);

        // 把字串陣列包進 ArrayAdapter,掛給 AutoCompleteTextView
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, autoStrs);
        actv.setAdapter(adapter);
    }
}

幾個實務提醒

預設的比對是「開頭相符」,所以輸入 ab 會命中 abc、abcd,但不会命中 ba。若想改成包含即命中,可以自訂 Adapter 改寫 getFilter()。

另外兩個常用設定:android:completionThreshold 決定輸入幾個字才開始提示,預設是 2;android:completionHint 可以自訂下拉清單上方的提示文字。真實專案裡,建議清單通常來自資料庫或網路 API,此時把 ArrayAdapter 換成自訂 Adapter,並搭配非同步載入即可,切忌在主執行緒上做網路請求。

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