Пользовательский фильтр SimpleAdapter

Я пытаюсь заставить свой фильтр работать на SimpleAdapter и, похоже, он падает на последнем препятствии. При отладке кода я вижу результирующий отфильтрованный ArrayList в itemsFiltered в методе publishResults, но полный список всегда отображается.

Как заставить адаптер работать с отфильтрованным списком результатов, а не с полным нефильтрованным списком?

Код является:

private class TextCharFilter extends Filter{

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {

        // convert search string to lower case - the filtering is not case sensitive
        constraint = constraint.toString().toLowerCase();

        // define the result object
        FilterResults result = new FilterResults();
        // define a place to hole the items that pass filtering         
        List<HashMap<String, String>> filteredItems = new ArrayList<HashMap<String,String>>();

        // loop through the original list and any items that pass filtering are added to the "filtered" list
        if(constraint != null && constraint.toString().length() > 0) {

            for(int i = 0; i < items.size(); i++) {
                HashMap<String, String> tmp = items.get(i);
                String candidate = tmp.get("PT").toLowerCase();

                if(candidate.contains(constraint) ) {
                    filteredItems.add(tmp);
                }
            }

            // set the result to the "filtered" list.
            result.count = filteredItems.size();
            result.values = filteredItems;

        }    
        else
        {
            // if nothing to filter on -  then the result is the complete input set
            synchronized(this)
            {
             result.values = items;
             result.count = items.size();
            }
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {

        ArrayList<HashMap<String, String>> tmp = (ArrayList<HashMap<String, String>>)results.values;

        itemsFiltered = new ArrayList<HashMap<String,String>>();

        for (int i = 0; i < tmp.size(); i++){
            itemsFiltered.add(tmp.get(i));
        }

        notifyDataSetChanged();

        notifyDataSetInvalidated();
    }

}

2 ответа

Решение

Похоже, что вы добавляете элементы в массив, созданный в publishResults(). элементы никогда не добавляются к фактическому адаптеру. Вы должны очистить адаптер в publishResults () и затем добавить элементы обратно. Или просто создать новый адаптер из списка фильтров и установить его в качестве адаптера вашего списка.

У меня такая же проблема.

Этот код работает для меня.

protected void publishResults(CharSequence constraint, FilterResults results) {
        arrayList.clear();
        arrayList.addAll((Collection<? extends HashMap<String, String>>) results.values);
        if (results.count > 0) {
            notifyDataSetChanged();
        } else {
            notifyDataSetInvalidated();
        }       
}
Другие вопросы по тегам