本文實(shí)例講述了Android開(kāi)發(fā)高級(jí)組件之自動(dòng)完成文本框(AutoCompleteTextView)用法。分享給大家供大家參考,具體如下:
通常來(lái)說(shuō)自動(dòng)完成文本框(AutoCompleteTextView)從EditText派生而出,實(shí)際上他也是一個(gè)編輯框,但他比普通的編輯框多了一個(gè)功能:當(dāng)用戶輸入一定字符后,自動(dòng)完成文本框會(huì)顯示一個(gè)下拉菜單,供用戶從中選擇,當(dāng)用戶選擇了某個(gè)菜單項(xiàng)過(guò)后,AutoCompleteTextView就會(huì)按用戶選擇自動(dòng)填寫(xiě)該文本框。
自動(dòng)完成文本框(AutoCompleteTextView),用于實(shí)現(xiàn)允許用戶輸入一定字符后,顯示一個(gè)下拉菜單,供用戶從中選擇,當(dāng)用戶選擇某個(gè)選項(xiàng)之后,按用戶選擇自動(dòng)填寫(xiě)該文本框。
語(yǔ)法格式:
<AutoCompleteTextView屬性列表></AutoCompleteTextView>
AutoCompleteTextView組件繼承EditText,所以它支持EditText組件提供的屬性,同時(shí),該組件還有以下屬性:
| 屬性 | 功能 |
|---|---|
| android:completionHint | 下拉列表下面的說(shuō)明性文字 |
| android:completionThreshold | 彈出下來(lái)列表的最小字符個(gè)數(shù) |
| android:dropDownAnchor | 下拉列表的錨點(diǎn)或掛載點(diǎn) |
| android:dropDownHeight | 下拉列表高度 |
| android:dropDownWidth | 下拉列表寬度 |
| android:dropDownHorizontalOffset | 下拉列表距離左邊的距離 |
| android:dropDownVerticalOffset | 下拉列表距離上邊的距離 |
| android:dropDownSelector | 下拉列表被選中的行的背景 |
| android:popupBackground | 下拉列表的背景 |
效果如下所示:

具體實(shí)現(xiàn)步驟:
界面布局 res/layout/main.xml:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" android:background="#000000"><AutoCompleteTextView android:layout_height="wrap_content" android:text="" android:id="@+id/autoCompleteTextView1" android:completionThreshold="2" android:completionHint="請(qǐng)輸入內(nèi)容" android:background="#333333" android:layout_marginLeft="10dp" android:layout_weight="7" android:layout_width="wrap_content" ></AutoCompleteTextView><Button android:text="搜索" android:id="@+id/button0" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:layout_marginLeft="10dp"/></LinearLayout>
MainActivity.java文件中:
首先設(shè)置保存下拉菜單列表項(xiàng)內(nèi)容:
//此字符串是要在下拉菜單中顯示的列表項(xiàng)private static final String[] COUNTRIES=new String[]{"jb51","jb51VEVB武林網(wǎng)","jb51腳本下載","jb51軟件下載","www.survivalescaperooms.com","VEVB武林網(wǎng)"}; onCreate()方法中獲取自動(dòng)完成文本框,并為自動(dòng)完成文本框設(shè)置適配器,具體實(shí)現(xiàn)代碼如下:
//獲取自動(dòng)完成文本框final AutoCompleteTextView textView=(AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1);//注意ArrayAdapter與SimpleAdapter的區(qū)別//創(chuàng)建一個(gè)ArrayAdapter適配器ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,COUNTRIES);textView.setAdapter(adapter);//為自動(dòng)完成文本框設(shè)置適配器
最后為搜索按鈕添加事件監(jiān)聽(tīng)器:
//為搜索按鈕添加事件監(jiān)聽(tīng)器button.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Toast.makeText(MainActivity.this, textView.getText().toString(),Toast.LENGTH_SHORT).show(); }});附:完整實(shí)例代碼點(diǎn)擊此處本站下載。
希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注