Android Support Library 22.1 was released yesterday. Many new features were added into the v4 support library and v7, among which android.support.v7.util.SortedList<T>
draws my attention.
It's said that, SortedList
is a new data structure, works with RecyclerView.Adapter
, maintains the item added/deleted/moved/changed animations provided by RecyclerView
. It sounds like a List<T>
in a ListView
but seems more advanced and powerful.
So, what is the difference between SortedList<T>
and List<T>
? How could I use it efficiently? What's the enforcement of SortedList<T>
over List<T>
if it is so? Could somebody post some samples of it?
Any tips or codes will be appreciated. Thanks in advance.
SortedList
is inv7 support library
.Here below is a sample of use of
SortedList
, I think it is what you want, take a look at it and enjoy!SortedList
handles the communication to the Recycler adapter viaCallback
.One difference between
SortedList
andList
is seen in theaddAll
helper method in the sample below.Say I have 10 cached items to load immediately when my recycler list is populated. At the same time, I query my network for the same 10 items because they could have changed since I cached them. I can call the same
addAll
method andSortedList
will replace the cachedItems with fetchedItems under the hood (always keeps the last added item).In a regular
List
, I would have duplicates of all my items (list size of 20). WithSortedList
its replaces items that are the same using the Callback'sareItemsTheSame
.When the fetchedItems are added,
onChange
will only be called if one or more of thePage
's title changed. You can customize whatSortedList
looks for in the Callback'sareContentsTheSame
.Sample
You can have a getter on your adapter for your
SortedList
, but I just decided to add helper methods to my adapter.Adapter Class:
Page class:
Viewholder xml:
Viewholder class:
There is a sample SortedListActivity in the support library source repository which demonstrates how to use SortedList and SortedListAdapterCallback inside a RecyclerView.Adapter. From the root of the SDK, with the support library installed, it should be at
extras/android/support/samples/Support7Demos/src/com/example/android/supportv7/util/SortedListActivity.java
(also on github).The existence of these particular samples is mentioned exactly once in Google's documentation, at the bottom of a page dealing with a different topic, so I don't blame you for not finding it.
About
SortedList
implementation, it is backed by an array of<T>
with a default min capacity of 10 items. Once the array is full the array is resized tosize() + 10
The source code is available here
From documentation
Regarding to performance they also added SortedList.BatchedCallback to carry out multiple operation at once instead of one at the time