在使用 LinearSmoothScroller 滚动 RecyclerView 时,出现这种问题是因为在其 computeScrollVectorForPosition() 方法中返回的向量不正确。所以我们需要重写该方法,以正确指示滚动方向。
下面是一个示例代码,可以在你的 RecyclerView.SmoothScroller 中调用,并返回正确的滚动向量:
public class CustomLinearSmoothScroller extends LinearSmoothScroller {
public CustomLinearSmoothScroller(Context context) {
super(context);
}
@Override
public PointF computeScrollVectorForPosition(int targetPosition) {
final int firstChildPos = getFirstChildPosition();
int direction = targetPosition < firstChildPos ? -1 : 1;
return new PointF(0, direction);
}
private int getFirstChildPosition(){
RecyclerView.LayoutManager layoutManager = getLayoutManager();
if (layoutManager == null || layoutManager.getChildCount() == 0) {
return RecyclerView.NO_POSITION;
}
View child = layoutManager.getChildAt(0);
return layoutManager.getPosition(child);
}
}
在你的 RecyclerView 中调用如下:
CustomLinearSmoothScroller scroller = new CustomLinearSmoothScroller(context);
scroller.setTargetPosition(targetPosition);
layoutManager.startSmoothScroll(scroller);