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

Android 學習筆記(十二):AutoCompleteTextView 自動完成輸入實作

編輯:關於 Android 開發

Android 學習筆記(十二):AutoCompleteTextView 自動完成輸入實作

本文探討如何實現輸入的自動匹配提示,就像在搜尋框中輸入時會即時顯示建議一樣。這主要用到兩個控件:AutoCompleteTextView 與 MultiAutoCompleteTextView。

它們與普通 TextView 的主要區別在於能自動匹配用戶輸入的內容,並多了一個關鍵屬性 android:completionThreshold="2",用於指定用戶輸入多少個字元時開始匹配(此處設為 2 個字元)。

一、AutoCompleteTextView 的實現

布局檔中的相關程式碼如下:

<AutoCompleteTextView
    android:id="@+id/autoCompleteTextView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignTop="@+id/textView1"
    android:hint="請輸入內容"
    android:textColor="#000000"
    android:completionThreshold="2" >
    <requestFocus />
</AutoCompleteTextView>

源碼中需定義並綁定適配器:

private AutoCompleteTextView auTextView;
String[] res = {"ab1", "ab2", "ab3", "ab4", "ab5"};

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    auTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
    // 定義適配器並添加
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_expandable_list_item_1, res);
    auTextView.setAdapter(adapter);
}

二、MultiAutoCompleteTextView 的實現

它與 AutoCompleteTextView 的主要區別在於可以多次匹配——只要定義了分隔符,就能對多段內容分別提示,而 AutoCompleteTextView 只能進行一次匹配。

布局檔程式碼:

<MultiAutoCompleteTextView
    android:id="@+id/multiAutoCompleteTextView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/autoCompleteTextView1"
    android:layout_marginTop="24dp"
    android:textColor="#000000"
    android:completionThreshold="2"
    android:hint="請輸入內容" />

源碼中除了綁定適配器外,還需設定分隔符:

private MultiAutoCompleteTextView muTextView;
String[] res = {"ab1", "ab2", "ab3", "ab4", "ab5"};

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_expandable_list_item_1, res);

    muTextView = (MultiAutoCompleteTextView) findViewById(R.id.multiAutoCompleteTextView1);
    muTextView.setAdapter(adapter);
    // 設置逗號分隔符
    muTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
}

補充說明:設定分隔符時使用的 MultiAutoCompleteTextView.CommaTokenizer() 是一個內建的逗號分隔符實作,它會以逗號作為分詞依據,讓多段內容能各自觸發自動完成提示。

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