要讓Android選擇框支持模糊搜索,可以通過自定義適配器來實現。下面是一個簡單的示例代碼:
public class CustomAdapter extends BaseAdapter implements Filterable {
private List<String> originalList;
private List<String> filteredList;
private Context context;
public CustomAdapter(List<String> originalList, Context context) {
this.originalList = originalList;
this.filteredList = originalList;
this.context = context;
}
@Override
public int getCount() {
return filteredList.size();
}
@Override
public Object getItem(int position) {
return filteredList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView textView = new TextView(context);
textView.setText(filteredList.get(position));
return textView;
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
List<String> filteredValues = new ArrayList<>();
for (String value : originalList) {
if (value.toLowerCase().contains(constraint.toString().toLowerCase())) {
filteredValues.add(value);
}
}
results.values = filteredValues;
results.count = filteredValues.size();
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredList = (List<String>) results.values;
notifyDataSetChanged();
}
};
}
}
List<String> dataList = new ArrayList<>();
// 添加數據到dataList中
AutoCompleteTextView autoCompleteTextView = findViewById(R.id.autoCompleteTextView);
CustomAdapter adapter = new CustomAdapter(dataList, this);
autoCompleteTextView.setAdapter(adapter);
通過以上步驟,就可以讓Android選擇框支持模糊搜索了。用戶在輸入框中輸入關鍵詞時,選擇框會自動篩選出包含該關鍵詞的選項并顯示出來。