Day4.2--Android高階UI控制元件之AutoCompleteTextView的使用
阿新 • • 發佈:2019-02-17
AutoCompleteTextView--自動不全文字檢視, 先來看下它的繼承關係:
可以看到,AutoCompleteTextView實際上是繼承自EditText的, 因此它也是一個可編輯的文字框那麼它也EditText得區別在哪裡呢, 看下動態圖所示:
從圖中可以看出,當用戶輸入相應數量的字元內容之後,會在文字框下方彈出一個提示的列表檢視,其中提示內容是以輸入字元開頭的。這也就是它和EditText的區別所在
接下來看一下如何在程式碼中使用AutoCompleteTextView。
首先在xml佈局檔案中,通過<AutoCompleteTextView>標籤新增檢視,如下程式碼所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <!-- 1、AutoCompleteTextView繼承自EditText, 因此EditText具有的屬性AutoCompleteTextView都可以使用 2、android:completionThreshold 指定輸入多少字元開始進行模糊搜尋 --> <AutoCompleteTextView android:id="@+id/autoCompleteTextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:completionThreshold="1" android:hint="請輸入單詞:"/> </LinearLayout>
注意:android:completionThreshold屬性預設值是2,也就是預設需要輸入2個字元時,才會彈出提示框資訊
接下來,看MainActivity.java中的程式碼, 如下所示:
// 1、初始化AutoCompleteTextView控制元件 AutoCompleteTextView autoText = (AutoCompleteTextView) findViewById( R.id.autoCompleteTextView); // 2、初始化資料來源 String[] data = new String[]{"abc", "abcdef", "asd", "bdef"}; // 3、初始化介面卡 ArrayAdapter<String> adapter = new ArrayAdapter<>( this, android.R.layout.simple_list_item_1, data); autoText.setAdapter(adapter);
這樣就將一個數組中的資料繫結到一個AutoCompleteTextView當中,假如在文字框中輸入a,則會彈出abc、abcdef、asd三個item提示。
注意:AutoCompleteTextView彈出的資訊,並不是模糊搜尋之後的結果,而是以輸入內容為開頭作為依據進行查詢
AutoCompleteTextView可以通過以下方式,設定彈出list的點選事件:
autoText.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView textView = (TextView) view;
Toast.makeText(MainActivity.this, textView.getText(), Toast.LENGTH_SHORT).show();
}
});