Skip to content

Instantly share code, notes, and snippets.

@VAdaihiep
Created October 29, 2015 08:26
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VAdaihiep/811711ae4644ff2bb76e to your computer and use it in GitHub Desktop.
Save VAdaihiep/811711ae4644ff2bb76e to your computer and use it in GitHub Desktop.
SnappingRecyclerView horizontal in simplest way. Original version: http://stackoverflow.com/a/29171652/1393920
package vn.mog.mygimi.home;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
public final class SnappingRecyclerView extends RecyclerView {
public SnappingRecyclerView(Context context) {
super(context);
}
public SnappingRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SnappingRecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean fling(int velocityX, int velocityY) {
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) getLayoutManager();
//these four variables identify the views you see on screen.
int lastVisibleView = linearLayoutManager.findLastVisibleItemPosition();
int firstVisibleView = linearLayoutManager.findFirstVisibleItemPosition();
View firstView = linearLayoutManager.findViewByPosition(firstVisibleView);
View lastView = linearLayoutManager.findViewByPosition(lastVisibleView);
//these variables get the distance you need to scroll in order to center your views.
//my views have variable sizes, so I need to calculate side margins separately.
//note the subtle difference in how right and left margins are calculated, as well as
//the resulting scroll distances.
int leftMargin = (getWidth() - lastView.getWidth()) / 2;
int rightMargin = (getWidth() - firstView.getWidth()) / 2 + firstView.getWidth();
int leftEdge = lastView.getLeft();
int rightEdge = firstView.getRight();
int scrollDistanceLeft = leftEdge - leftMargin;
int scrollDistanceRight = rightMargin - rightEdge;
//if(user swipes to the left)
if (velocityX > 0) smoothScrollBy(scrollDistanceLeft, 0);
else smoothScrollBy(-scrollDistanceRight, 0);
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment