Illustration by Ella Dobson

Restore RecyclerView scroll position

Florina Muntenescu
May 4, 2020 · 2 min read

You might have had the problem where a RecyclerView loses the scroll position when your Activity/Fragment is re-created. This usually happens because the Adapter data is loaded asynchronously and data hasn’t loaded by the time RecyclerView needs to layout so it fails to restore the scroll position.

Starting with 1.2.0-alpha02, RecyclerView offers a new API to let the Adapter block layout restoration until it is ready. Read on to learn how to use this new API and how it works.

Restoring the scroll position

The recyclerview:1.2.0-alpha02 solution is a new Adapter method which allows you to set a state restoration policy (via the StateRestorationPolicy enum). This has 3 options:

  • ALLOW — the default state, that restores the RecyclerView state immediately, in the next layout pass
  • PREVENT_WHEN_EMPTY — restores the RecyclerView state only when the adapter is not empty (adapter.getItemCount() > 0). If your data is loaded async, the RecyclerView waits until data is loaded and only then the state is restored. If you have default items, like headers or load progress indicators as part of your Adapter, then you should use the PREVENT option, unless the default items are added using ConcatAdapter (find out more here). ConcatAdapter waits for all of its adapters to be ready and only then it restores the state.
  • PREVENT — all state restoration is deferred until you set ALLOW or PREVENT_WHEN_EMPTY.

Set the state restoration policy on the adapter like this:

adapter.stateRestorationPolicy = PREVENT_WHEN_EMPTY

That’s it! A short and sweet post to get you up to date with RecyclerView’s lazy state restoration feature. Start using it 🏁👩‍💻👨‍💻!

Android Developers

The official Android Developers publication on Medium

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store