RecyclerView snapping with SnapHelper
The 24.2.0 version of the support library introduced two new classes (SnapHelper and LinearSnapHelper) that should be used to handle snapping in a RecyclerView.
You’ve probably already noticed this in the Google Play app:
As you can see, the RecyclerView snaps to the first item in the adapter.
If you use the default LinearSnapHelper, you can only snap to the center.
The only code needed is:
This produces the following result:
To replicate the Google Play behavior, we need to override the calculateDistanceToFinalSnap and findSnapView methods of the LinearSnapHelper to find the start view and calculate the distance needed to snap it to the correct position.
To make this easier to do, I created a GravitySnapHelper that supports snapping in 4 directions (start, top, end, bottom).
If you want the same behavior as the Google Play app, now you only need to change the previous code to:
Make sure you set the appropriate orientation in the LayoutManager too:
Here’s a complete example:
This sample is available on my Github: https://github.com/rubensousa/RecyclerViewSnap/