在Fragment中使用搜索栏来过滤RecyclerView的内容,可以按照以下步骤进行操作:
以下是一个示例代码:
public class MyFragment extends Fragment {
private EditText searchEditText;
private RecyclerView recyclerView;
private MyAdapter adapter;
private List<DataItem> dataList;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, container, false);
// 初始化搜索栏和RecyclerView
searchEditText = view.findViewById(R.id.search_edit_text);
recyclerView = view.findViewById(R.id.recycler_view);
// 初始化数据源
dataList = new ArrayList<>();
// 添加数据项到数据源
// 创建适配器
adapter = new MyAdapter(dataList);
// 设置布局管理器和适配器
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
// 监听搜索栏的文本变化事件
searchEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
// 获取搜索关键字
String keyword = s.toString().toLowerCase(Locale.getDefault());
// 调用适配器的过滤方法
adapter.getFilter().filter(keyword);
}
});
return view;
}
private class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> implements Filterable {
private List<DataItem> originalDataList;
private List<DataItem> filteredDataList;
public MyAdapter(List<DataItem> dataList) {
this.originalDataList = dataList;
this.filteredDataList = dataList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
// 创建ViewHolder
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
// 绑定ViewHolder
}
@Override
public int getItemCount() {
return filteredDataList.size();
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
String keyword = constraint.toString().toLowerCase(Locale.getDefault());
List<DataItem> filteredList = new ArrayList<>();
for (DataItem item : originalDataList) {
// 根据搜索关键字过滤数据
if (item.getName().toLowerCase(Locale.getDefault()).contains(keyword)) {
filteredList.add(item);
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
results.count = filteredList.size();
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredDataList = (List<DataItem>) results.values;
notifyDataSetChanged();
}
};
}
private class ViewHolder extends RecyclerView.ViewHolder {
// ViewHolder的代码
}
}
private class DataItem {
private String name;
// 数据项的其他属性和方法
}
}
这样,当用户在搜索栏中输入关键字时,RecyclerView会根据关键字过滤数据,并实时更新显示的内容。
领取专属 10元无门槛券
手把手带您无忧上云