How to implement search in CustomListView based on class item of POJO class in Android?

前端 未结 1 1575
挽巷
挽巷 2020-11-30 16:01

I have a Custom Listview. I have to display data from the webserver. I need to implement search based on input from EditText. Each row in ListView Contains Image, Title and

相关标签:
1条回答
  • 2020-11-30 16:33

    You want your adapter to implement Filterable. Then override getFilter to perform the search

    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                if (results != null && results.count >= 0) {
                    setData(results.values);
                } else {
                    setData(mPostingData);
                }
    
                notifyDataSetInvalidated();
            }
    
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults result = new FilterResults();
                if (!TextUtils.isEmpty(constraint)) {
                    constraint = constraint.toString().toLowerCase();
                    ArrayList<PostData> currentItems = new ArrayList<PostData>();
                    ArrayList<PostData> foundItems = new ArrayList<PostData>();
    
                    currentItems.addAll(mPostingData);
    
                    for (PostData post: currentItems){
                        // Search for the items here. If we get a match, add to the list
                        if (post.mType.toLowerCase().contains(constraint)) {
                            foundItems.add(m);
                        } else if .... {
                        }
                    }
    
                    result.count = foundItems.size();
                    result.values = foundItems;
                } else {
                    result.count = -1;
                }
    
                return result;
            }
        };
    }
    

    You would then call the search from the activity with adapter.getFilter().filter("Search Query").

    This will replace the list of items in your listview with the search results too.

    0 讨论(0)
提交回复
热议问题