不清楚您说“smoothScroll”是什么意思。您可能指的是自动滚动到指定位置的自动“smoothScrollToPosition”,您可能是在谈论手动滚动,也可能是在谈论投掷。为了繁荣,我现在将尝试回答所有这些问题。
1.自动平滑滚动。
在您的布局管理器中,您需要实现smoothScrollToPosition 方法:
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, State state, int position)
{
// A good idea would be to create this instance in some initialization method, and just set the target position in this method.
LinearSmoothScroller smoothScroller = new LinearSmoothScroller(getContext())
{
@Override
public PointF computeScrollVectorForPosition(int targetPosition)
{
int yDelta = calculateCurrentDistanceToPosition(targetPosition);
return new PointF(0, yDelta);
}
// This is the important method. This code will return the amount of time it takes to scroll 1 pixel.
// This code will request X milliseconds for every Y DP units.
@Override
protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics)
{
return X / TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, Y, displayMetrics);
}
};
smoothScroller.setTargetPosition(position);
startSmoothScroll(smoothScroller);
}
在本例中,我使用了一个名为“calculateCurrentDistanceToPosition”的辅助方法。这可能有点棘手,因为它涉及跟踪您当前的滚动位置,并计算给定 y 位置的滚动位置。您可以找到一个示例,说明如何跟踪回收商的滚动 y here。
计算给定位置的滚动 y 实际上取决于您的回收站显示的内容。假设您的所有物品的高度相同,您可以通过执行以下计算来计算:
targetScrollY = targetPosition * itemHeight
然后,要计算需要滚动的距离,只需用目标滚动 y 减去当前滚动 y:
private int calculateCurrentDistanceToPosition(int targetPosition) {
int targetScrollY = targetPosition * itemHeight;
return targetScrollY - currentScrollY;
}
2。减慢手动滚动速度。
再次,您需要编辑布局管理器,这次是 scrollVerticallyBy 方法:
@Override
public int scrollVerticallyBy(int delta, Recycler recycler, State state)
{
// write your limiting logic here to prevent the delta from exceeding the limits of your list.
int prevDelta = delta;
if (getScrollState() == SCROLL_STATE_DRAGGING)
delta = (int)(delta > 0 ? Math.max(delta * MANUAL_SCROLL_SLOW_RATIO, 1) : Math.min(delta * MANUAL_SCROLL_SLOW_RATIO, -1));
// MANUAL_SCROLL_SLOW_RATIO is between 0 (no manual scrolling) to 1 (normal speed) or more (faster speed).
// write your scrolling logic code here whereby you move each view by the given delta
if (getScrollState() == SCROLL_STATE_DRAGGING)
delta = prevDelta;
return delta;
}
编辑:在上述方法中,我调用“getScrollState()”。这是RecyclerView的方法。在这个实现中,我的自定义LayoutManager 是我的自定义RecyclerView 的嵌套类。如果这对你不起作用,你可以尝试通过一些界面模式来获取滚动状态。
3.放慢投掷速度
在这里,您想缩小投掷速度。您需要在 RecyclerView 子类中覆盖 fling 方法:
@Override
public boolean fling(int velocityX, int velocityY)
{
velocityY *= FLING_SCALE_DOWN_FACTOR; // (between 0 for no fling, and 1 for normal fling, or more for faster fling).
return super.fling(velocityX, velocityY);
}
我很难提供更量身定制的解决方案,因为您没有发布任何代码,也没有提供有关您的设置的太多信息,但我希望这涵盖了大多数基础并帮助您找到最适合您的解决方案.