RecyclerView 滚动到指定position

思路是:先用scrollToPosition,将要置顶的项先移动显示出来,然后计算这一项离顶部的距离,用scrollBy完成最后的100米!
关键代码
先传入要置顶第几项,然后区分情况处理

    private void moveToPosition(int n) {
        this.mIndex = n;
        int firstItem = this.mLinearLayoutManager.findFirstVisibleItemPosition();
        int lastItem = this.mLinearLayoutManager.findLastVisibleItemPosition();
        System.out.println(firstItem + "  " + lastItem);
        if(n <= firstItem) {
            this.recyclerView.scrollToPosition(n);
        } else if(n <= lastItem) {
            int top = this.recyclerView.getChildAt(n - firstItem).getTop();
            this.recyclerView.scrollBy(0, top);
        } else {
            this.recyclerView.scrollToPosition(n);
            this.move = true;
        }

    }

RecyclerView滚动监听

class RecyclerViewListener extends RecyclerView.OnScrollListener{
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            //在这里进行第二次滚动(最后的100米!)
            if (move ){
                move = false;
                //获取要置顶的项在当前屏幕的位置,mIndex是记录的要置顶项在RecyclerView中的位置
                int n = mIndex - mLinearLayoutManager.findFirstVisibleItemPosition();
                if ( 0 <= n && n < mRecyclerView.getChildCount()){
                    //获取要置顶的项顶部离RecyclerView顶部的距离
                    int top = mRecyclerView.getChildAt(n).getTop();
                    //最后的移动
                    mRecyclerView.scrollBy(0, top);
                }
            }
        }
    }

你可能感兴趣的:(RecyclerView 滚动到指定position)