RecyclerView losses the scroll position how to restore

Hello developers,
 You may have had the issue where a RecyclerView loses the scroll position when your Activity/Fragment is re-instantiated. This generally happens on the grounds that the Adapter information is stacked nonconcurrently or asynchronously and data hasn't stacked when RecyclerView needs to the layout so it neglects to reestablish the scroll position.



in starting of version 1.2.0-alpha02, RecyclerView has a change in its API regarding the Adapter, 
to let the adapter block UI(layout) rebuilding until it is prepared.

How to restore the scroll position?

There are a few different ways to guarantee a right scroll position that you may have received. The best one is ensuring that you constantly set the data on the Adapter before the primary design(first layout) pass by storing the information you need to show in memory, in a ViewModel, or in a repository. In the event that this methodology was unimaginable, different arrangements were either increasingly confounded, such as abstaining from setting the Adapter on the RecyclerView, which can carry issues with things like headers, or misusing LayoutManager.onRestoreInstanceState API.

the new API recyclerview:1.2.0-alpha02 have new adapter method which allows setting rebuilding rules(using StateRestorationPolicy enum)

the StateRestorationPolicy have three-options
  1. ALLOW
  2. PREVENT_WHEN_EMPTY
  3. PREVENT
ALLOW:
this is the default state, and it restore the recyclerview state immediately.

PREVENT_WHEN_EMPTY:
Reestablishes the RecyclerView state just when the adapter isn't empty (adapter.getItemCount() > 0). On the off chance that your data is loaded async, the RecyclerView holds up until data is loaded and at exactly that point the state is reestablished. In case you have default items, similar to headers or load progress indicators as a feature of your Adapter, at that point you should utilize the PREVENT, except if the default items are included utilizing MergeAdapter.MergeAdapter trusts that the entirety of its adapters will be prepared and at exactly that point it reestablishes the state.

PREVENT: 
All state rebuilding is conceded until you set ALLOW or PREVENT_WHEN_EMPTY.

How to set?
Set the state policy like this,
adapter.stateRestorationPolicy=PREVENT_WHEN_EMPTY;

if your recyclerView losses the position, plz try this one.
 

No comments:

Post a Comment