Restore Recycler View State

Swatiomar
2 min readApr 10, 2021

Sharing knowledge is the most fundamental act of friendship. Because it is a way you can give something without loosing something.
-Richard Stallman

Most of the developers facing the problem of restore the recycler view position when view recreated (on rotation). But Finally Android come up with StateRestorationPolicy to solve this problem. So, Let’s get deep dive into this article and after reading this article please try with yourself….

Starting from 1.2.0-alpha02, Recycler View introduces a new API to let the Adapter block layout restoration until it is ready.

State Restoration Policy has 3 states.
ALLOW
PREVENT_WHEN_EMPTY
PREVENT

ALLOW

This is the default state. It restores the Recycler View state immediately, in the next layout pass.

This is useful when you have an sync operation as you are setting adapter with the result as soon as you initialize. Since it restore state immediately but you are setting adapter after you get the response from network call. So it will take some time to show that. So it is not useful with asynchronous operation.

PREVENT_WHEN_EMPTY

As the name implies, It restores the Recycler View state only when the adapter item is not empty.

This one is suitable with both synchronous and asynchronous operations For asynchronous operations, Recycler View state will be restore only after you update your adapter with the data.
For synchronous operations, It will provide same result as async operations. Populating the adapter with the list during adapter initialization.

PREVENT

All state restoration is deferred until you set ALLOW or PREVENT_WHEN_EMPTY.

If you used prevent restoration policy and forget to use ALLOW or PREVENT_WHEN_EMPTY then recycler view state will not be restore. You have to set the ALLOW or PREVENT_WHEN_EMPTY when you got the results to restore the recycler view state.

I will also soon be publishing it on GeeksforGeeks https://www.geeksforgeeks.org/

To get better understanding and coding part, Please go through YouTube link for demo app and GitHub link for coding part:
Demo App : https://youtu.be/5syrnl9EDW0
GitHub Link : https://github.com/swatiomar27/Constraint-Layout-Demo

Happy Coding :)

I hope you liked the article. Feel free to share any feedback. And stay tuned for more concepts!

Don’t forget to follow me on Medium. If you liked the article, click the clap below so more people can see it!

Thanks !!!

--

--

Swatiomar

As a programmer, to keep learning and help ones who needs the skills to be a master, I am available to be a part of an adventurous journey….