Android組件系列(1):自動(dòng)完成輸入內(nèi)容的組件(AutoCompleteTextView )
本文為原創(chuàng),如需轉(zhuǎn)載,請注明作者和出處,謝謝!
AutoCompleteTextView和EditText組件類似,都可以輸入文本。但AutoCompleteTextView組件可以和一個(gè)字符串?dāng)?shù)組或List對(duì)象綁定,當(dāng)用戶輸入兩個(gè)及以上字符時(shí),系統(tǒng)將在AutoCompleteTextView組件下方列出字符串?dāng)?shù)組中所有以輸入字符開頭的字符串,這一點(diǎn)和www.Google.com的搜索框非常相似,當(dāng)輸入某一個(gè)要查找的字符串時(shí),Google搜索框就會(huì)列出以這個(gè)字符串開頭的最熱門的搜索字符串列表。
AutoCompleteTextView組件在XML布局文件中使用<AutoCompleteTextView>標(biāo)簽來表示,該標(biāo)簽的使用方法與<EditText>標(biāo)簽相同。如果要讓AutoCompleteTextView組件顯示輔助輸入列表,需要使用AutoCompleteTextView類的setAdapter方法指定一個(gè)Adapter對(duì)象,代碼如下:
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);
運(yùn)行上面代碼后,在文本框中輸入“手機(jī)”,就會(huì)顯示如圖1所示的效果。
除了AutoCompleteTextView組件外,我們還可以使用MultiAutoCompleteTextView組件來完成連續(xù)輸入的功能。也就是說,當(dāng)輸入完一個(gè)字符串后,在該字符串后面輸入一個(gè)逗號(hào)(,),在逗號(hào)前后可以有任意多個(gè)空格,然后再輸入一個(gè)字符串(例如,“手機(jī)”),仍然會(huì)顯示輔助輸入的列表,但要使用MultiAutoCompleteTextView類的setTokenizer方法指定MultiAutoCompleteTextView.CommaTokenizer類的對(duì)象實(shí)例(該對(duì)象表示輸入多個(gè)字符串時(shí)的分隔符為逗號(hào)),代碼如下:
(MultiAutoCompleteTextView) findViewById(R.id.multiAutoCompleteTextView);
multiAutoCompleteTextView.setAdapter(adapter);
multiAutoCompleteTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
運(yùn)行上面的代碼后,在屏幕的第2個(gè)文本框中輸入“ab , ”后,再輸入“手機(jī)”,會(huì)顯示如圖2所示的效果。
《Android開發(fā)完全講義(第2版)》(本書版權(quán)已輸出到臺(tái)灣)
http://product.dangdang.com/product.aspx?product_id=22741502
《Android高薪之路:Android程序員面試寶典 》http://book.360buy.com/10970314.html
新浪微博:http://t.sina.com.cn/androidguy 昵稱:李寧_Lining
posted on 2010-04-21 14:53 銀河使者 閱讀(2796) 評(píng)論(0) 編輯 收藏 所屬分類: java 、 原創(chuàng) 、移動(dòng)(mobile)