We all Android users has Google Play app in our mobile. And ofcourse you’ll see the amazing UI of that application. If you want to use that RecycleView design in your Android application. Then this tutorial is just for you where we discuss about RecyclerView Snapping library.
Lets complete our intro with an RecyclerView Snapping Example:
Hopefully you’ve probably already noticed this in the Google Play app and now lets begin the implementation of this library.
If you need snapping support to start, top, end or bottom, use GravitySnapHelper.
Add this to your build.gradle:
Otherwise, center snapping is done with LinearSnapHelper (part of the recyclerview-v7 package).
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:
SnapHelper snapHelper = new LinearSnapHelper(); snapHelper.attachToRecyclerView(recyclerView);
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:
SnapHelper snapHelper = new GravitySnapHelper(Gravity.START); snapHelper.attachToRecyclerView(startRecyclerView);
Make sure you set the appropriate orientation in the LayoutManager too:
// HORIZONTAL for Gravity START/END and VERTICAL for TOP/BOTTOM recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
Snapping start with GravitySnapHelper:
startRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)); SnapHelper snapHelperStart = new GravitySnapHelper(Gravity.START); snapHelperStart.attachToRecyclerView(startRecyclerView);
Snapping top with GravitySnapHelper:
topRecyclerView.setLayoutManager(new LinearLayoutManager(this)); SnapHelper snapHelperTop = new GravitySnapHelper(Gravity.TOP); snapHelperTop.attachToRecyclerView(topRecyclerView);
Here’s a complete example:
Download this library
[button color=”blue” size=”” type=”3d” target=”_blank” link=”https://github.com/rubensousa/RecyclerViewSnap/archive/master.zip”]Download project here[/button]
Hope you like this article!!!