The missing piece in implementing a cards carousel using a RecyclerView!
Edit: I’ve replaced this story with a more elaborate mini-series explaining how to further ViewPager-ize a RecyclerView:
With the birth of
RecyclerView in Android SDK v22.1.0, Google have introduced a genuine improvement in the quality of UI infrastructure Android has to offer for developers. Providing an impressive amount of extensibility and flexibility without giving up on a hint of performance, RecyclerView has effectively made older solutions such as
And so it does allow for quite a similar behavior in the naïve use case:
ViewPager has also been renowned for providing a ‘page by page’ solution for views that do not necessarily take up the whole screen. For example, with minimal tweaking, you can set up this list of Cards:
Try to do that with a
PagerSnapHelper out of the box and you will fail miserably. As pointed out in the docs, they kind’a don’t want that to fall through:
PagerSnapHelper can help achieve a similar behavior to
ViewPager. Set both
RecyclerViewand the items of the
MATCH_PARENTheight and width and then attach PagerSnapHelper to the
An Item Decorator To The Rescue!
So as I’ve previously pointed out, RecyclerView is super flexible, allowing this to be fixed nevertheless using a simple decorator:
In essence, the decorator simply pads each view so it would artificially fit the screen — also allowing for a ‘hint’ at the previous and next card to show next to it.
So assuming we want each card (or whatever view you have) to take up 80% of the total screen’s width, and the neighbouring cards to show 1% on each side as a hint— as in the screenshot, all it takes is to apply the decorator, like so:
Is this restricted to PagerSnapHelper?
Absolutely not. The decorator stands in its own right, and can be used even if all you’re looking for is just proper padding.
While this narrows the gap between the full-featured
ViewPager and the
ViewPager supports scrollable “paged” layouts much better. For example, With
ViewPager it’s much easier to monitor which page is currently the one in focus on the screen, and the overall scrolling state (could be interesting in case you wish to apply adaptive transformations over the views).
I’ll try to tackle these kind of gaps in upcoming posts.
In the meantime, hope you’ve enjoyed this post!