要在Android中實現EditText的自動提示功能,可以使用AutoCompleteTextView控件。AutoCompleteTextView是EditText的子類,可以在用戶輸入時顯示一組可能的建議。
以下是實現EditText的自動提示功能的步驟:
<AutoCompleteTextView
android:id="@+id/autoCompleteTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter text here"
android:completionThreshold="1" />
AutoCompleteTextView autoCompleteTextView = findViewById(R.id.autoCompleteTextView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, suggestions);
autoCompleteTextView.setAdapter(adapter);
String[] suggestions = {"Apple", "Banana", "Cherry", "Date", "Elderberry", "Fig", "Grape"};
autoCompleteTextView.setThreshold(1); // 設置觸發建議的最小字符數
autoCompleteTextView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
// 根據用戶輸入內容過濾建議列表
List<String> filteredSuggestions = new ArrayList<>();
for (String suggestion : suggestions) {
if (suggestion.toLowerCase().contains(s.toString().toLowerCase())) {
filteredSuggestions.add(suggestion);
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_dropdown_item_1line, filteredSuggestions);
autoCompleteTextView.setAdapter(adapter);
}
});
通過以上步驟,您就可以在Android中實現EditText的自動提示功能了。用戶在輸入時會看到一個下拉列表,展示可能的建議,用戶可以從中選擇一個建議填充到EditText中。