具有自定义ArrayAdapter和Filter的AutoCompleteTextView

时间:2011-12-23 09:40:19

标签: android filter android-arrayadapter autocompletetextview

当我尝试从LogCat中过滤AutoCompleteTextView中的结果时遇到问题我知道过滤执行正确但是没有刷新视图:/我忘记了任何建议或帮助吗?

以下是过滤器的源代码。

@Override
public Filter getFilter() {
    Filter myFilter = new Filter() {

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            Log.i(TAG, "Perform filtering with constraint: " + constraint.toString());
            List<String> resultsSuggestions = new ArrayList<String>();
            Log.i(TAG, "COUNT: " + getCount());
            for (int i = 0; i < getCount(); i++) {
                if(getItem(i).getSuggestionValue().startsWith(constraint.toString())){
                    Log.i(TAG, "ADDED");
                    resultsSuggestions.add(getItem(i).getSuggestionValue());
                }
            }
            FilterResults results = new FilterResults();
            results.values = resultsSuggestions;
            results.count = resultsSuggestions.size();
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            if (results != null && results.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    };
    return myFilter;
}

2 个答案:

答案 0 :(得分:2)

缺少的部分是我需要从过滤器设置新值,所以我只是简单地改变了

publushResults();

现在它正在运作。正确的代码如下。

    @Override
    @SuppressWarnings("unchecked")
    protected void publishResults(CharSequence constraint, FilterResults results) {
        clear();
        ArrayList<Suggestions> newValues = (ArrayList<Suggestions>) results.values;
        for (int i = 0; i < newValues.size(); i++) {
            add(newValues.get(i));
        }
        if(results.count>0){
            notifyDataSetChanged();
        } else{
            notifyDataSetInvalidated();
        }
    }

答案 1 :(得分:1)

另一个更新 - 在输入和删除搜索文本框中的所有字符时,很快就会崩溃newValues.size()或newValues.get(i)上的应用程序,因为newValues可能为null。所以,这是你应该使用的代码:

@Override
    @SuppressWarnings("unchecked")
    protected void publishResults(CharSequence constraint, FilterResults results) {
        clear();
        ArrayList<Suggestions> newValues = (ArrayList<Suggestions>) results.values;
        if(newValues !=null) {
            for (int i = 0; i < newValues.size(); i++) {
                add(newValues.get(i));
            }
            if(results.count>0){
                notifyDataSetChanged();
            } else{
                notifyDataSetInvalidated();
        }
    }