Android Search in ListView not working properly

眉间皱痕 提交于 2019-12-24 14:23:57

问题


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 :

In 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) {
        }
    };

In 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!


回答1:


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.



来源:https://stackoverflow.com/questions/18109744/android-search-in-listview-not-working-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!