How to sort RecyclerView item in android
Before passing the data to RecyclerView
adapter
data.sort(new Comparator<Datum>() {
@Override
public int compare(Datum o1, Datum o2) {
return o1.get(position).getMessageId().compareTo(o2.get(position).getMessageId());
}
});
then pass (notify) the sorted list to the adapter.
A simpler solution for someone still stuck on the same
Collections.sort(data, new Comparator<CustomData>() {
@Override
public int compare(CustomData lhs, CustomData rhs) {
return Integer.compare( rhs.getId(),lhs.getId());
}
});
YourAdapter adapter = new YourAdapter(context, data);
//Setup Linear or Grid Layout manager
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(adapter);
in Kotlin use like this after loading data in array:
myItems.sortWith(Comparator { lhs, rhs ->
// -1 - less than, 1 - greater than, 0 - equal, all inversed for descending
if (lhs.name > rhs.name) -1 else if (lhs.id < rhs.id) 1 else 0
})
After that apply:
myItemAdapter.notifyDataSetChanged()
try this before passing your list to the adapter (after API call and before adapter notifydatasetchanged):
Collections.sort(data, new Comparator<CustomData>() {
@Override
public int compare(CustomData lhs, CustomData rhs) {
// -1 - less than, 1 - greater than, 0 - equal, all inversed for descending
return lhs.getId() > rhs.getId() ? -1 : (lhs.customInt < rhs.customInt ) ? 1 : 0;
}
});