实现效果
如果我们需要实现点击RecyclerView 列表定位到中间的位置,如下图
一般情况下,RecyclerView 的列表滚动到指定位置,我们会使用 RecyclerView 的 smoothScrollToPosition()
,但是问题有两个:
- 不会定位到中间位置。
- 当滚动的目标位置在屏幕中时,不会滚动。
实现方法
- 新建 CenterLayoutManager 类继承 LinearLayoutManager 类,重写
smoothScrollToPosition()
方法。在此类中,新建 CenterSmoothScroller 类继承 LinearSmoothScroller 类,重写calculateDtToFit()
方法。
public class CenterLayoutManager extends LinearLayoutManager {
public CenterLayoutManager(Context context) {
super(context);
}
public CenterLayoutManager(Context context, int orientation, boolean reverseLayout) {