要解決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完全顯示,避免底部超出屏幕。