背景
接到个产品需求,需要使RecyclerView点击item后滚动到RecyclerView的中间位置
思路
通过自定义LayoutManager
- 自定义SmoothScroller继承LinearSmoothScroller
- 继承LinearLayoutManager重写smoothScrollToPosition调用自定义SmoothScroller
- 搞清楚calculateDtToFit方法中int viewStart, int viewEnd, int boxStart, int boxEnd的含义计算滚动位置
下面是摘取的部分LinearSmoothScroller的源码
//LinearSmoothScroller源码中调用calculateDtToFit方法的入参
//top = item view的顶部
final int top = layoutManager.getDecoratedTop(view) - params.topMargin;
//bottom = item view的底部
final int bottom = layoutManager.getDecoratedBottom(view) + params.bottomMargin;
//start = RecyclerView 的顶部
final int start = layoutManager.getPaddingTop();
//end = RecyclerView 的顶部
final int end = layoutManager.getHeight() - layoutManager.getPaddingBottom