1

I have a horizontal recyclerView that has 28 elements. I want to achieve the following: display only 7 items at once and if the user swipes to the right then scroll to the next 7 items and same if swipes to the left then scroll to the previous 7 items. I have tried to solve it with the LinearSnapHelper like this:

public class CustomSnapHelper extends LinearSnapHelper {
    @Override
    public int findTargetSnapPosition(RecyclerView.LayoutManager layoutManager, int velocityX, int velocityY) {
        View centerView = findSnapView(layoutManager);
        if (centerView == null) {
            return RecyclerView.NO_POSITION;
        }

        int position = layoutManager.getPosition(centerView);
        int targetPosition = -1;
        if (layoutManager.canScrollHorizontally()) {
            if (velocityX < 0) {
                targetPosition = position - 7;
            } else {
                targetPosition = position + 7;
            }
        }
        final int firstItem = 0;
        final int lastItem = layoutManager.getItemCount() - 1;
        targetPosition = Math.min(lastItem, Math.max(targetPosition, firstItem));
        return targetPosition;
    }
}

But the problems are

  1. If I drag the list and scroll a few positions and release it then it won't go back to the original snapped position.
  2. Sometimes (based on the velocity) If I swipe to right when the first 7 item is displayed, then it scrolls an additional space and snaps to the wrong position and the items from 9-15 are displayed.
Community
  • 1
  • 1
cylon
  • 735
  • 1
  • 11
  • 26

0 Answers0