Skip to content

Instantly share code, notes, and snippets.

@tejpratap46
Created February 13, 2017 12:10
Show Gist options
  • Save tejpratap46/d8593dbbed9b4245ef3b12abca4e6ebb to your computer and use it in GitHub Desktop.
Save tejpratap46/d8593dbbed9b4245ef3b12abca4e6ebb to your computer and use it in GitHub Desktop.
Android RecyclerView Snap Adapter
// Horizontal snap adapter for recycler view, LinearSnapHelper is available from support lib 24.2.0
LinearSnapHelper snapHelper = new LinearSnapHelper() {
@Override
public int findTargetSnapPosition(RecyclerView.LayoutManager lm, int velocityX, int velocityY) {
View centerView = findSnapView(lm);
if (centerView == null)
return RecyclerView.NO_POSITION;
int position = lm.getPosition(centerView);
int targetPosition = -1;
if (lm.canScrollHorizontally()) {
if (velocityX < 0) {
targetPosition = position - 1;
} else {
targetPosition = position + 1;
}
}
if (lm.canScrollVertically()) {
if (velocityY < 0) {
targetPosition = position - 1;
} else {
targetPosition = position + 1;
}
}
final int firstItem = 0;
final int lastItem = lm.getItemCount() - 1;
targetPosition = Math.min(lastItem, Math.max(targetPosition, firstItem));
return targetPosition;
}
};
snapHelper.attachToRecyclerView(recyclerViewThumbnail);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment