I'm trying to implement a Horizontal scrolling recycler view with only one scroll at a time.
I've used following LinearSnapHelper to centralize the view
public LinearSnapHelper getSnapHelper() {
return 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;
}
};
}
And then I've attached my horizontal recycler view to snaphelper as follow :
getSnapHelper().attachToRecyclerView(accountSelectionRecyclerView);
This works near perfect and centralize item as expected.
But I want to restrict my recycler view to scroll only one item at a time.
To achieve that I've created a custom recycler view to control the fling of the my recycler but still it has no effect and I can able to scroll to two,three items if I swipe with full force.
public class HorizontalRecyclerView extends RecyclerView {
public HorizontalRecyclerView(Context context) {
super(context);
}
public HorizontalRecyclerView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public HorizontalRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean fling(int velocityX, int velocityY) {
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) getLayoutManager();
int lastVisibleView = linearLayoutManager.findLastVisibleItemPosition();
int firstVisibleView = linearLayoutManager.findFirstVisibleItemPosition();
View firstView = linearLayoutManager.findViewByPosition(firstVisibleView);
View lastView = linearLayoutManager.findViewByPosition(lastVisibleView);
int leftMargin = (DeviceDetailsSingleton.getInstance().getScreenWidth() - lastView.getWidth()) / 2;
int rightMargin = (DeviceDetailsSingleton.getInstance().getScreenWidth() - firstView.getWidth()) / 2 + firstView.getWidth();
int leftEdge = lastView.getLeft();
int rightEdge = firstView.getRight();
int scrollDistanceLeft = leftEdge - leftMargin;
int scrollDistanceRight = rightMargin - rightEdge;
if (velocityX > 0)
smoothScrollBy(scrollDistanceLeft, 0);
else
smoothScrollBy(-scrollDistanceRight, 0);
return true;
}
}
With normal swipe speed it's working perfectly.