带有建议的文本框

Text box with suggestions

我目前正在使用 AutoCompleteTextView,其中包含一个术语列表,可在用户输入时提供建议。但是,我想使用一种不同的字符串算法,而不是简单地检查一个字符串是否包含您的搜索词,它比较两个字符串的接近程度(例如搜索 "chcken" 应该显示 "chicken")。

我已经生成了一个方法,它接受一个字符串参数 - 您的搜索查询 - 和 returns 数据库中根据相关性匹配该查询的排序字符串数组。如何让 AutoCompleteTextView 使用该数组?我不能在每次击键时简单地将它附加到适配器,因为这不会改变 AutoCompleteTextView 的固有行为,仅显示数组中与字符串查询匹配的元素。

您可以在适配器中实现自定义过滤器。

示例:

public class MyFilterableAdapter extends ListAdapter<String> implements Filterable {

    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            public String convertResultToString(Object resultValue) {
                return (String) resultValue;
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults filterResults = new FilterResults();
                filterResults.values = filteredArray;
                filterResults.count = filteredArray.size();
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                if (results != null && results.count > 0) {
                    //here you will need to update the array where you are controlling what shows in the list
                    notifyDataSetChanged();
                }
            }
        };
    }
}

由于您没有提供任何代码,我不知道您使用的是什么适配器,但您需要实现所有适配器方法(getCount、getView 等)。

您可以在这些问题中找到更多信息:

Autocompletetextview with custom adapter and filter