android recyclerview scroolToPosition

boolean move = false;
    int mIndex = 0;

    private void moveToPosition(int index) {
        mIndex = index;
        LinearLayoutManager linearLayoutManager = (LinearLayoutManager) comment_rl.getLayoutManager();
        //获取当前recycleView屏幕可见的第一项和最后一项的Position
        int firstItem = linearLayoutManager.findFirstVisibleItemPosition();
        int lastItem = linearLayoutManager.findLastVisibleItemPosition();
        //然后区分情况
        if (index <= firstItem) {
            //当要置顶的项在当前显示的第一个项的前面时
            comment_rl.scrollToPosition(index);
        } else if (index <= lastItem) {
            //当要置顶的项已经在屏幕上显示时,计算它离屏幕原点的距离
            int top = comment_rl.getChildAt(index - firstItem).getTop();
            comment_rl.scrollBy(0, top);
        } else {
            //当要置顶的项在当前显示的最后一项的后面时
            comment_rl.scrollToPosition(index);
            //记录当前需要在RecyclerView滚动监听里面继续第二次滚动
            move = true;
        }
    }

    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) {
            super.onScrolled(recyclerView, dx, dy);
            //在这里进行第二次滚动(最后的距离)
            if (move) {
                move = false;
                //获取要置顶的项在当前屏幕的位置,mIndex是记录的要置顶项在RecyclerView中的位置
                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) comment_rl.getLayoutManager();
                int n = mIndex - linearLayoutManager.findFirstVisibleItemPosition();
                if (0 <= n && n < comment_rl.getChildCount()) {
                    //获取要置顶的项顶部离RecyclerView顶部的距离
                    int top = comment_rl.getChildAt(n).getTop();
                    //最后的移动
                    comment_rl.scrollBy(0, top);
                }
            }

        }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值