在Android中,可以使用RecyclerView和Adapter來處理列表數據的排序和過濾。以下是一些常見的方法:
public void sortData(Comparator<T> comparator) {
Collections.sort(originalDataList, comparator);
notifyDataSetChanged();
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterPattern = constraint.toString().toLowerCase().trim();
List<T> filteredList = new ArrayList<>();
for (T item : originalDataList) {
if (item.toString().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
dataList.clear();
dataList.addAll((List<T>) results.values);
notifyDataSetChanged();
}
};
}
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;
}
});
通過以上方法,可以實現在Android應用中對列表數據進行排序和過濾操作。