How to use SnapHelper in RecyclerView in Android Application?
What is SnapHelper?
SnapHelper is a helper class that helps in snapping any child view of the RecyclerView. For example, you can snap the firstVisibleItem of the RecyclerView as you must have seen in the play store application that the firstVisibleItem will be always completely visible when scrolling comes to the idle position.
Android already provides a helper class to do the same. The class is LinearSnapHelper which will only enable the center snapping.
You just need to do the following changes in your code:
SnapHelper snapHelper = new LinearSnapHelper(); snapHelper.attachToRecyclerView(yourRecyclerView);
Now, how to do start snapping like below?
First of all, you will have to create a class let say StartSnapHelper which will be extending LinearSnapHelper and mainly override the following methods:
Override this method to snap to a particular point within the target view or the container view on any axis. This method is called when the SnapHelper has intercepted a fling and it needs to know the exact distance required to scroll by in order to snap to the target view.
Override this method to provide a particular target view for snapping. This method is called when the SnapHelper is ready to start snapping and requires a target view to snap to. It will be explicitly called when the scroll state becomes idle after a scroll. It will also be called when the SnapHelper is preparing to snap after a fling and requires a reference view from the current set of child views. If this method returns
null, SnapHelper will not snap to any view.
Now, attach this to your RecyclerView.
SnapHelper startSnapHelper = new StartSnapHelper(); startSnapHelper.attachToRecyclerView(yourRecyclerView);
Here, you can find the complete sample app.
Happy Coding 🙂