RecyclerView滚动到指定位置

2024-03-21  本文已影响0人  电梯里漫舞

首先定义一个滚动辅助类

 LinearSmoothScroller linearSmoothScroller = new LinearSmoothScroller(_mActivity) {
                    @Override
                    protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
                        return super.calculateSpeedPerPixel(displayMetrics);
                    }

                    @Override
                    protected int getHorizontalSnapPreference() {
                        return LinearSmoothScroller.SNAP_TO_START;
                    }

                    @Override
                    protected int getVerticalSnapPreference() {
                        return LinearSmoothScroller.SNAP_TO_START;
                    }
                };

在RecyclerView设置LayoutManager时复写方法

mRvBloodBags.setLayoutManager(new LinearLayoutManager(_mActivity) {
            @Override
            public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
                linearSmoothScroller.setTargetPosition(position);
                startSmoothScroll(linearSmoothScroller);
            }
        });

在需要滚动的地方调用方法

        mRvBloodBags.smoothScrollToPosition(pos);
上一篇 下一篇

猜你喜欢

热点阅读