我将 Recyclerview 与 CardView 一起使用。我知道如何控制 ListView 的速度。但不适用于 Recyclerview。
我在找到的类名中搜索了很多 SmoothScroll .怎么用?我不知道!现在 Recyclerview 默认滚动很快。
更新:
我用 this 总结了 Gil 的答案
最佳答案
不清楚您所说的“smoothScroll
”是什么意思。您可能指的是自动滚动到指定位置的自动“smoothScrollToPosition
”,您可能是在谈论手动滚动,也可能是在谈论 throw 。为了繁荣,我现在将尝试回答所有这些问题。
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.放慢 throw 速度
在这里你想缩小 throw 速度。您需要覆盖 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);
}
我很难提供更量身定制的解决方案,因为您没有发布任何代码,也没有提供有关您的设置的太多信息,但我希望这涵盖了大多数基础并帮助您找到最适合您的解决方案.
关于安卓 : Control Smooth scroll over recycler view,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28803319/