android

如何让Android选择框支持模糊搜索

小樊
147
2024-07-25 00:19:13
栏目: 编程语言

要让Android选择框支持模糊搜索,可以通过自定义适配器来实现。下面是一个简单的示例代码:

  1. 首先,创建一个自定义的适配器类,继承自BaseAdapter,并实现Filterable接口:
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();
            }
        };
    }
}
  1. 在Activity或Fragment中使用自定义适配器类:
List<String> dataList = new ArrayList<>();
// 添加数据到dataList中

AutoCompleteTextView autoCompleteTextView = findViewById(R.id.autoCompleteTextView);
CustomAdapter adapter = new CustomAdapter(dataList, this);
autoCompleteTextView.setAdapter(adapter);

通过以上步骤,就可以让Android选择框支持模糊搜索了。用户在输入框中输入关键词时,选择框会自动筛选出包含该关键词的选项并显示出来。

0
看了该问题的人还看了