在RecyclerViewAdapter中添加搜索功能可以通过以下步骤实现:
以下是一个示例代码:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<String> originalData;
private List<String> filteredData;
public MyAdapter(List<String> data) {
originalData = data;
filteredData = new ArrayList<>(data);
}
@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 filteredData.size();
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
String keyword = constraint.toString().toLowerCase();
List<String> filteredList = new ArrayList<>();
for (String item : originalData) {
if (item.toLowerCase().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) {
filteredData = (List<String>) results.values;
notifyDataSetChanged();
}
};
}
public static class ViewHolder extends RecyclerView.ViewHolder {
// ViewHolder的实现
}
}
在Activity或Fragment中的搜索框监听文本变化事件,并调用适配器的getFilter().filter()方法进行搜索:
EditText searchEditText = findViewById(R.id.search_edit_text);
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) {
adapter.getFilter().filter(s.toString());
}
});
这样,当用户在搜索框中输入关键字时,RecyclerView会根据关键字过滤显示相应的数据项。
领取专属 10元无门槛券
手把手带您无忧上云