我尝试实现一次只有一个滚动的水平滚动回收器视图。
我使用了以下LinearSnapHelper来集中视图
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;
}
};
}
然后我将我的水平回收视图附加到snaphelper,如下所示:
getSnapHelper().attachToRecyclerView(accountSelectionRecyclerView);
这符合预期的近乎完美和集中的项目。
但我想限制我的回收者视图一次只滚动一个项目。
为了实现这一点,我创建了一个自定义回收站视图来控制我的回收器的投掷,但它仍然没有效果,如果我用力量滑动,我可以滚动到两个,三个项目。
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;
}
}
使用正常的滑动速度,它可以正常工作。