ListView中的Android搜索无法正常工作 [英] Android Search in ListView not working properly

查看:65
本文介绍了ListView中的Android搜索无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将搜索功能添加到具有自定义适配器的ListView中.当我在EditText中键入内容时,它会搜索并完全显示结果,但是如果我尝试擦除刚写的内容,它将不会出现在初始列表中,而是保留在已过滤的列表中. 这是代码:

I'm trying to add the search functionality to a ListView that has a custom adapter. When I type something in the EditText it searches and shows the results corectly but if I try to erase what I just wrote it won't come out with the initial list, it will stay with the already filtered list. Here is the code :

在MainActivity中:

private TextWatcher searchTextWatcher = new TextWatcher() {
    @Override
        public void onTextChanged(CharSequence s, int start, int before, int count)     {
              adapter.getFilter().filter(s.toString());
              adapter.notifyDataSetChanged();
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int     after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };

在LazyAdapter中:

public Filter getFilter() {
    return new Filter() {
        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            data = (ArrayList<HashMap<String, String>>) results.values;
            LazyAdapter.this.notifyDataSetChanged();
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            ArrayList<HashMap<String, String>> filteredResults = getFilteredResults(constraint);

            FilterResults results = new FilterResults();
            results.values = filteredResults;

            return results;
        }
    };
}

protected ArrayList<HashMap<String, String>> getFilteredResults(
        CharSequence constraint) {
    ArrayList<HashMap<String, String>> filteredTeams = new ArrayList<HashMap<String, String>>();
    for(int i=0;i< data.size();i++){
        if(data.get(i).get(MainActivity.KEY_TITLE).toLowerCase().startsWith(constraint.toString().toLowerCase())){
            filteredTeams.add(data.get(i));
        }
    }

    return filteredTeams;
}

我的代码有什么问题? 谢谢!

What is wrong with my code? Thank you!

推荐答案

请注意,进行过滤时,您要用过滤后的结果替换ArrayList中未过滤的结果.当您按退格键删除字符时,您现在正尝试根据已过滤的列表进行过滤,这就是结果不变的原因.您将需要保留对原始数据集的引用,该引用未应用任何过滤器,并且始终使用该过滤器进行过滤,但永远不要更改/替换它.

Realize that when you filter you are replacing your unfiltered results in your ArrayList with your filtered results. When you hit backspace to delete characters you are trying to now filter based on your already filtered list which is why your results won't change. You will need to keep a reference to your original data set that doesn't have any filter applied to it and always filter using that, but never change/replace it.

这篇关于ListView中的Android搜索无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆