RecyclerView滚动到指定位置

RecyclerView向我们提供了若干个方法来进行滚动:
(1).scrollTo(int x, int y)
Set the scrolled position of your view.
(2).scrollBy(int x, int y)
Move the scrolled position of your view.
(3).scrollToPosition(int position)
Convenience method to scroll to a certain position. RecyclerView does not implement scrolling logic, rather forwards the call to RecyclerView.LayoutManager.scrollToPosition(int)
前面2个方法需要我们去控制移动的距离,自己计算高度或者宽度。在动态的布局中且各项样式高度可能都不一样的情况下,比较有难度。
使用第3个方法scrollToPosition时,移动到当前屏幕可见列表的前面的项时,它会将要显示的项置顶。但是移动到后面的项时,一般会显示在最后的位置。
因此,综合以上两个方法,我们可以先用scrollToPosition方法,将要置顶的项先移动显示出来,然后计算这一项离顶部的距离,用scrollBy完成最后距离的滚动。

1.让置顶的那一项在当前屏幕可见

private void scrollToNextShotDate(List<BabyVaccineGroup> vaccineGroupList) {
        LinearLayoutManager linearLayoutManager = (LinearLayoutManager) getRecyclerView().getLayoutManager();
        //获取当前RecycleView屏幕可见的第一项和最后一项的Position
        int firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition();
        int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();
        if (nextPosition < firstVisibleItemPosition) {
            //要置顶的项在当前显示的第一项之前
            getRecyclerView().smoothScrollToPosition(nextShotPosition);
        } else if (nextPosition < lastVisibleItemPosition) {
            //要置顶的项已经在屏幕上显示,计算它离屏幕原点的距离
            int top = getRecyclerView().getChildAt(nextShotPosition - firstVisibleItemPosition).getTop();
            getRecyclerView().smoothScrollBy(0, top);
        } else {
            //要置顶的项在当前显示的最后一项之后
            mShouldScroll = true;
            getRecyclerView().smoothScrollToPosition(nextShotPosition);
        }
    }

2.添加滚动监听,当完成第一次滚动后,进行第二次的滚动

private class RcvScrollListener extends RecyclerView.OnScrollListener {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if (mShouldScroll && newState == RecyclerView.SCROLL_STATE_IDLE) {
                mShouldScroll = false;
                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) getRecyclerView().getLayoutManager();
                int n = nextPosition - linearLayoutManager.findFirstVisibleItemPosition();
                if (n >= 0 && n < getRecyclerView().getChildCount()) {
                    //获取要置顶的项顶部距离RecyclerView顶部的距离
                    int top = getRecyclerView().getChildAt(n).getTop();
                    //进行第二次滚动(最后的距离)
                    getRecyclerView().smoothScrollBy(0, top);
                }
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

        }
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容