4

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.

Community
  • 1
  • 1
neits
  • 1,805
  • 1
  • 14
  • 32

2 Answers2

2

You can't change sorting strategy dynamically because sorted list has a single sorted order for each instance(there is no method for "do sorting again").

You can use

recyclerView.swapAdapter(newAdapter, false);` 

If you have stable id's in your adapter, you will get a nice animation. Because swapAdapter() helps RecyclerView to re-use view holders.

cokceken
  • 2,038
  • 9
  • 22
1

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.

kor
  • 141
  • 5