您好,登錄后才能下訂單哦!
要實現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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。