按对象内的值过滤RecyclerView

时间:2019-05-18 20:23:23

标签: java android android-recyclerview

我有一个RecyclerView,它向片段返回对象列表,我希望片段仅显示在其变量之一中具有特定值的对象。我该怎么办?

这是我在片段上调用适配器的方式:

RecyclerView recyclerview = view.findViewById(R.id.list);

if (recyclerview != null) {
    Context context = view.getContext();
    adapter = new MyHospitalHistoryRecyclerViewAdapter(DummyContent.ITEMS, mListener);
    recyclerview.setAdapter(adapter);
}

return view;

DummyContent.ITEMSDummyItems类型的列表。

有人知道我该怎么做吗?我已经测试了我所知道的一切

1 个答案:

答案 0 :(得分:1)

尝试在适配器中添加过滤器逻辑,例如:

class MyAdapter extends RecyclerView.Adapter<MyViewHolder> implements Filterable {
      private mFilter = new NewFilter();
      private List<MyData> mItems;
      private List<MyData> mFiltered = new ArrayList<>();     // <--- use this collection in all required getItemsCount and onBindViewHolder methods

      public Filter getFilter {
            return mFilter;
      }

      public class NewFilter extends Filter {
            @Override
            protected FilterResults performFiltering(CharSequence charSequence) {
                mFiltered .clear();
                final FilterResults results = new FilterResults();
                if(charSequence.length() == 0){
                    mFiltered .addAll(mItems);
                }else{
                    final String filterPattern =charSequence.toString().toLowerCase().trim();
                    for(MyData item: mItems) {
                        if(item.getMyProperty().toLowerCase().contains(filterPattern)){ // replace this condition with actual you need
                            mFilteredItems.add(item);
                        }
                    }
                }
                results.values = mFilteredItems;
                results.count = mFilteredItems.size();
                return results;
            }

            @Override
            protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
                this.mAdapter.notifyDataSetChanged();
            }
        }

然后,您可以将其与片段一起使用:

adapter.filter("hello");

上面的行仅使用“ myProperty”属性中包含“ hello”的项目更新列表。