2019-12-06 RecyclerView 实现滑动、跳转到

2019-12-06  本文已影响0人  猫KK

如标题,这里只针对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)
上一篇下一篇

猜你喜欢

热点阅读