gpt4 book ai didi

java - 按对象内部的值过滤 RecyclerView

转载 作者:行者123 更新时间:2023-12-02 09:52:43 25 4
gpt4 key购买 nike

我有一个 RecyclerView,它将对象列表返回到 fragment ,我希望 fragment 仅显示在其变量之一中具有特定值的对象。我怎样才能做到这一点?

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

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 类型列表。

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

最佳答案

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

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

@Override
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();
}
}

然后你可以在 fragment 中使用它:

adapter.getFilter().filter("hello");

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

关于java - 按对象内部的值过滤 RecyclerView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56202576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com