在RecyclerView中实现SearchView可以通过以下步骤完成:
以下是一个示例代码:
// 步骤1:创建RecyclerView
RecyclerView recyclerView = findViewById(R.id.recyclerView);
// 步骤2:创建数据源
List<String> dataList = new ArrayList<>();
dataList.add("Item 1");
dataList.add("Item 2");
// 添加更多数据...
// 步骤3:创建适配器
MyAdapter adapter = new MyAdapter(dataList);
// 步骤4:设置适配器
recyclerView.setAdapter(adapter);
// 步骤5:实现搜索功能
SearchView searchView = findViewById(R.id.searchView);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return true;
}
});
// 步骤6:过滤数据
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> implements Filterable {
private List<String> dataList;
private List<String> filteredList;
public MyAdapter(List<String> dataList) {
this.dataList = dataList;
this.filteredList = dataList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
String item = filteredList.get(position);
holder.textView.setText(item);
}
@Override
public int getItemCount() {
return filteredList.size();
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
String keyword = constraint.toString().toLowerCase(Locale.getDefault());
List<String> filteredData = new ArrayList<>();
if (keyword.isEmpty()) {
filteredData = dataList;
} else {
for (String item : dataList) {
if (item.toLowerCase(Locale.getDefault()).contains(keyword)) {
filteredData.add(item);
}
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = filteredData;
return filterResults;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredList = (List<String>) results.values;
notifyDataSetChanged();
}
};
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView textView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.textView);
}
}
}
这样,就可以在RecyclerView中实现SearchView的搜索功能了。根据具体需求,可以自定义适配器的布局和数据类型。
领取专属 10元无门槛券
手把手带您无忧上云