Mario Muresean
Mario Muresean

Reputation: 273

How to scroll only one item by one in recyclerview?

I have a horizontal list which it's using a recycler view and a PagerSnapHelper to simulate a view pager. I want to swipe scroll one element at the time, but the problem is that i can scroll to the last element with one swipe.

So my problem is that I want to stop the swipe after one element swiped so if someone has any advice will be appreciated.

Upvotes: 4

Views: 1774

Answers (1)

rahu1613
rahu1613

Reputation: 121

You could try adding a logic by checking the current position as mentioned in below post:

SnapHelper Item Position

  public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if(newState == RecyclerView.SCROLL_STATE_IDLE) {
                View centerView = snapHelper.findSnapView(mLayoutManager);
                int pos = mLayoutManager.getPosition(centerView);
                Log.e("Snapped Item Position:",""+pos);
            }
        }

or Something like this:

LinearSnapHelper snapHelper = new 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 - 1;
            } else {
                targetPosition = position + 1;
            }
        }

        if (layoutManager.canScrollVertically()) {
            if (velocityY < 0) {
                targetPosition = position - 1;
            } else {
                targetPosition = position + 1;
            }
        }

        final int firstItem = 0;
        final int lastItem = layoutManager.getItemCount() - 1;
        targetPosition = Math.min(lastItem, Math.max(targetPosition, firstItem));
        return targetPosition;
    }
};
snapHelper.attachToRecyclerView(recyclerView);

Ref: https://ogeek.cn/qa/?qa=441913/&show=441914

Upvotes: 2

Related Questions