2019-12-06 RecyclerView 实现滑动、跳转到某个Position并顶置

如标题,这里只针对LinearLayoutManager的情况,滑动并顶置
新建一个TopSmoothScroller类

public class TopSmoothScroller extends LinearSmoothScroller {
    public TopSmoothScroller(Context context) {
        super(context);
    }

    @Override
    protected int getHorizontalSnapPreference() {
        //设置水平滑动并顶置
        return SNAP_TO_START;
    }

    @Override
    protected int getVerticalSnapPreference() {
        //设置垂直滑动并顶置
        return SNAP_TO_START;
    }

    @Override
    protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
        //返回值,设置滑动速度
        return super.calculateSpeedPerPixel(displayMetrics);
    }
}

在需要滑动的地方设置

    fun move(position: Int) {
        var smoothScroller = TopSmoothScroller(this)
        smoothScroller.targetPosition = position
        recyclerview.layoutManager?.startSmoothScroll(smoothScroller)
    }

这样就能实现滑动到某个position并顶置
如果需要实现跳转并顶置,即跳转到recyclerview列表是,第一个直接显示某个postion,只需要下面这样

 var layoutManager = recyclerview.layoutManager as LinearLayoutManager
 layoutManager.scrollToPositionWithOffset(moveIndex, LinearSmoothScroller.SNAP_TO_START)

你可能感兴趣的:(2019-12-06 RecyclerView 实现滑动、跳转到某个Position并顶置)