要实现RecyclerView列表项的快速搜索功能,可以通过以下步骤实现:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> implements Filterable {
private List<String> data;
private List<String> filteredData;
public MyAdapter(List<String> data) {
this.data = data;
this.filteredData = new ArrayList<>(data);
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
List<String> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(data);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (String item : data) {
if (item.toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData.clear();
filteredData.addAll((List<String>) results.values);
notifyDataSetChanged();
}
};
}
// Adapter中的其他方法
}
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private EditText searchEditText;
private MyAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
searchEditText = findViewById(R.id.searchEditText);
List<String> data = new ArrayList<>();
// 添加数据到data
adapter = new MyAdapter(data);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
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) {
adapter.getFilter().filter(s);
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。