I'm using a SortedList
which is used for filtering of the data in the RecyclerView
in regards to the current query in a SearchView
as described in How to filter a RecyclerView with a SearchView.
The problem is that the order of items must be able to change as well. The SortedList
interacts with the Adapter
through a Callback
class that has a compare
method. I would need to change it if the user changes the way the items are sorted but I am not sure how I can do that.
The current situation calls only for the reversal of the order, so this problem could be solved with a LinearLayoutManager
with setReversedLayout(true)
but I would be interested in how I can provide a completely different way of sorting the items in the SortedList
.
SortedList
API doesn't support dynamic changes of the conditions under which the list is sorted. It is designed to support changes of sorting criteria of a particular item or a batch of items at once. For example, supported scenario could be when item X priority value increases, and the list is sorted by priority. But not when the sorting condition changes to sorting by date.
Your case is the best solved the way you did, with setReversedLayout()
. Another (relatively clean) approach could be to instantiate a new SortedList with a different instance of SortedList.Callback
that supports the new sorting, add all items from the old list, instruct the ViewHolder
to use the new list instead, and trigger notifyDataSetChanged()
on the Adapter
.