recyclerview 点击滚动到顶部

本文详细介绍了如何在RecyclerView中实现指定条目滑动到顶部的功能。通过两步操作:首先确保目标条目出现在屏幕上,然后计算并执行滚动到顶部的偏移量。在滚动完成后,利用onScrollStateChanged方法进行回调,实现平滑滚动到目标位置。这种方法适用于RecyclerView,不同于ListView的精确返回定位。

1.背景

recyclerview不像listview一样,有精确的返回到固定位置的方法。recyclerview触发指定item到顶部,也是通过两部分处理的。
1.让指定的条目出现到屏幕里,然后计算该条目距离父容器顶端的距离,
2.然后执行向上滑动指定距离,也就实现了滑动到顶部的需求。

2.code

//如点击触发,该pos的item 滑动到顶部
 smoothMoveToPosition(recyclerView, pos);


//根据不同的情况,让条目滚动到屏幕内,然后计算偏移量。
private void smoothMoveToPosition(RecyclerView mRecyclerView, final int position) {

        if (position < 0)
            return;
		
        int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0));

        int lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1));
        Log.d(TAG, "smoothMoveToPosition: " + position);
        if (position < firstItem) {
            mRecyclerView.smoothScrollToPosition(position);
        } else if (position <= lastItem) {

            int movePosition = position - firstItem;
            //计算选中的item,距离顶部的偏移量
            if (movePosition >= 0 && movePosition < mRecyclerView.getChildCount()) {
                int top = mRecyclerView.getChildAt(movePosition).getTop();

                mRecyclerView.smoothScrollBy(0, top - mTitleHeight);
            }
        } else {
            // 第三种可能:跳转位置在最后可见项之后,则先调用smoothScrollToPosition将要跳转的位置滚动到可见位置
            // 再通过onScrollStateChanged控制再次调用smoothMoveToPosition,执行上一个判断中的方法
            mRecyclerView.smoothScrollToPosition(position);
            mToPosition = position;
            mShouldScroll = true;
        }
    }


		//onScrollStateChanged 中,当滚动完成,再次执行滚动
      if (mShouldScroll && RecyclerView.SCROLL_STATE_IDLE == scrollState) {
          mShouldScroll = false;
          smoothMoveToPosition(recyclerView, mToPosition);
      }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值