You may have encountered situations in development where RecyclerView loses the scrolling position information it previously held after an Activity/Fragment is recreated. Usually, this situation occurs because the Adapter data is loaded asynchronously and the data is not loaded when RecyclerView needs to be laid out, so the RecyclerView cannot be restored to its previous scrolling position.
Starting with version 1.2.0-Alpha02, Jetpack RecyclerView provides a new API that allows Adapter to block layout behavior until data is loaded, thereby avoiding loss of scrolling position information. We’ll show you how to use this new API and how it works.
Restore to original rolling position
There are several methods you can use to restore RecyclerView to its correct scrolling position, and you may have used these methods in real projects. One of the best ways to do this is to cache the data in memory, ViewModel, or Repository ahead of time, and then make sure that the cached data is set up into Adapter before the first layout comes in. If this method is not possible for your project, you can also use other methods, which are either more complicated (for example, avoid setting Adapter in RecyclerView, but this may cause display problems for items like headers). Or will cause LayoutManager. OnRestoreInstanceState API being abused.
Recyclerview: The solution provided in 1.2.0-Alpha02 is to introduce a new Adapter method that allows you to set its state recovery policy (via the enumeration type StateRestorationPolicy). It has three options:
- ALLOW – Default state, RecyclerView state will be restored immediately after the next layout is completed;
- PREVENT_WHEN_EMPTY – Restore RecyclerView only if adapter is not empty (adapter.getitemcount () > 0). If you load data asynchronously, RecyclerView waits until the data is loaded before restoring the state. If the Adapter has some default item, such as a header or load Progress Indicator, then you should use the PREVENT option, unless the ConcatAdapter adds the default item for more details. See Using ConcatAdapter to connect other Adapters sequentially. Concatadapters wait for all adapters to be ready before resuming their state.
- PREVENT – All state restores will not be executed until you set ALLOW or PREVENT_WHEN_EMPTY.
The adapter state recovery policy can be set using the following example code:
adapter.stateRestorationPolicy = PREVENT_WHEN_EMPTY
Copy the code
In this short article, you can learn about lazy State restoration of RecyclerView. Get started!