本文為原創,如需轉載,請注明作者和出處,謝謝!
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
新浪微博:http://t.sina.com.cn/androidguy 昵稱:李寧_Lining