RecyclerView实现缓慢smoothScrollToPosition

154 阅读1分钟

在Android中,可以通过smoothScrollToPosition实现滑动到Recyclerview的指定位置,过程相对较快,现在需要实现一个缓慢的滑动过程。 1,自定义一个滑动的线性布局管理类

public class ScrollLinearLayoutManager extends LinearLayoutManager {
    private final float MILLISECONDS_PER_INCH = 4f;//数值越大速度越慢
    public ScrollLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }
    @Override
    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
        LinearSmoothScroller linearSmoothScroller = new LinearSmoothScroller(recyclerView.getContext()) {
                    @Override
                    public PointF computeScrollVectorForPosition(int targetPosition) {
                        return ScrollLinearLayoutManager.this.computeScrollVectorForPosition(targetPosition);
                    }
                    @Override
                    protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
                        return MILLISECONDS_PER_INCH / displayMetrics.density;
                    }
                };
        linearSmoothScroller.setTargetPosition(position);
        startSmoothScroll(linearSmoothScroller);
    }
}

2,在定义Recyclerview的地方调用自定义的布局管理类

ScrollLinearLayoutManager layoutManager = new ScrollLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.smoothScrollToPosition(pos);//在合适的地方调用smoothScrollToPosition函数