1. 程式人生 > >Android元件系列(1):自動完成輸入內容的元件(AutoCompleteTextView )

Android元件系列(1):自動完成輸入內容的元件(AutoCompleteTextView )

本文為原創,如需轉載,請註明作者和出處,謝謝!

    AutoCompleteTextView EditText 元件類似,都可以輸入文字。但 AutoCompleteTextView 元件可以和一個字串陣列或 List 物件繫結,當用戶輸入兩個及以上字元時,系統將在 AutoCompleteTextView 組 件下方列出字串陣列中所有以輸入字元開頭的字串,這一點和 www.Google.com 的搜尋框非常相似,當輸入某一個要查詢的字串時, Google 搜尋框就會列出以這個字串開頭 的最熱門的搜尋字串列表。

    AutoCompleteTextView

元件在 XML 佈局檔案中使用 <AutoCompleteTextView> 標籤來表示,該標籤的使用方法與 <EditText> 標籤相同。如果要讓 AutoCompleteTextView 元件顯示輔助輸入列表,需要使用 AutoCompleteTextView 類的 setAdapter 方法指定一個 Adapter 物件,程式碼如下:

String[] autoString  = new  String[]{  " a " " ab " " abc " " bb " " bcd " " bcdf " " 手 機 "
" 手機作業系統 " " 手 機軟體 "  };
ArrayAdapter
< String >  adapter  = new  ArrayAdapter < String > ( this ,
android.R.layout.simple_dropdown_item_1line, autoString);
AutoCompleteTextView autoCompleteTextView 
=  
        (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
autoCompleteTextView.setAdapter(adapter);

執行上面程式碼後,在文字框中輸入“手機”, 就會顯示如圖 1 所 示的效果。


    除了 AutoCompleteTextView 組 件外,我們還可以使用 MultiAutoCompleteTextView 元件來完成連續輸入的功能。也就是說,當輸入完一個字串後,在該字串後面輸入一個逗號( , ),在逗號前後可以有任意多個空格,然後 再輸入一個字串(例如,“手機”),仍然會顯示輔助輸入的列表,但要使用 MultiAutoCompleteTextView 類的 setTokenizer 方法指定 MultiAutoCompleteTextView.CommaTokenizer 類的物件例項(該物件表示輸入多個字串時的分隔符為逗號),程式碼如下:

MultiAutoCompleteTextView multiAutoCompleteTextView  =  
        (MultiAutoCompleteTextView) findViewById(R.id.multiAutoCompleteTextView);
multiAutoCompleteTextView.setAdapter(adapter);
multiAutoCompleteTextView.setTokenizer(
new  MultiAutoCompleteTextView.CommaTokenizer());

  執行上面的程式碼後,在螢幕的第 2 個文字框中輸入“ ab , ” 後,再輸入“手機”,會顯示如圖 2 所示的效果。


2 U' i1 B1 Y9 ?+ m  p4 /1 x/ x