在Android中,實現自動補全功能可以使用AutoCompleteTextView組件。AutoCompleteTextView是一個可以顯示建議列表的EditText,當用戶輸入時,會根據輸入內容自動過濾和顯示建議列表。以下是實現自動補全功能的步驟:
<AutoCompleteTextView
android:id="@+id/autoCompleteTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="請輸入內容" />
// 創建一個字符串數組,用于存放建議列表數據
String[] suggestions = new String[]{"Apple", "Banana", "Orange", "Grape", "Peach"};
// 創建一個ArrayAdapter,將字符串數組作為數據源
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, suggestions);
AutoCompleteTextView autoCompleteTextView = findViewById(R.id.autoCompleteTextView);
autoCompleteTextView.setAdapter(adapter);
setThreshold()
方法設置閾值:autoCompleteTextView.setThreshold(2); // 設置閾值為2,輸入兩個字符才開始顯示建議列表
setFilter()
方法設置自定義的過濾器,以實現更靈活的過濾邏輯。這樣,你就成功實現了一個基本的自動補全功能。當用戶在AutoCompleteTextView中輸入內容時,會根據輸入內容自動顯示建議列表。