要解决RecyclerView在调用smoothScrollToPosition
后最后一个item底部超出屏幕的问题,可以使用自定义的LinearSmoothScroller
,使其底部对齐屏幕。步骤如下:
-
创建自定义的SmoothScroller类:
继承LinearSmoothScroller
并重写getVerticalSnapPreference
方法,指定对齐方式为底部(SNAP_TO_END
)。
public class BottomSmoothScroller extends LinearSmoothScroller {public BottomSmoothScroller(Context context) {super(context);}@Overrideprotected int getVerticalSnapPreference() {return LinearSmoothScroller.SNAP_TO_END; // 对齐到底部}@Overridepublic PointF computeScrollVectorForPosition(int targetPosition) {LinearLayoutManager layoutManager = (LinearLayoutManager) getLayoutManager();if (layoutManager == null) {return null;}return layoutManager.computeScrollVectorForPosition(targetPosition);}
}
-
使用自定义Scroller滚动到指定位置:
在需要滚动到最后一个item时,使用自定义的BottomSmoothScroller
。
int lastPosition = getItemCount() - 1;
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
BottomSmoothScroller smoothScroller = new BottomSmoothScroller(recyclerView.getContext());
smoothScroller.setTargetPosition(lastPosition);
layoutManager.startSmoothScroll(smoothScroller);
解释:
-
SNAP_TO_END:确保目标item的底部与RecyclerView的底部对齐,使整个item可见。
-
computeScrollVectorForPosition:根据布局方向计算滚动向量,支持垂直或水平布局。
此方法通过调整滚动对齐方式,确保最后一个item完全显示,避免底部超出屏幕。