天天看點

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所 示的效果。

Android 元件系列(1):自動完成輸入内容的元件(AutoCompleteTextView )本文為原創,如需轉載,請注明作者和出處,謝謝!

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

MultiAutoCompleteTextView multiAutoCompleteTextView = 

        (MultiAutoCompleteTextView) findViewById(R.id.multiAutoCompleteTextView);

multiAutoCompleteTextView.setAdapter(adapter);

multiAutoCompleteTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());

運作上面的代碼後,在螢幕的第2個文本框中輸入“ab ,  ” 後,再輸入“手機”,會顯示如圖2所示的效果。

Android 元件系列(1):自動完成輸入内容的元件(AutoCompleteTextView )本文為原創,如需轉載,請注明作者和出處,謝謝!

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

繼續閱讀