跟随RecyclerView滚动的算法

public class FollowScrollListener extends RecyclerView.OnScrollListener {
    private int MAX_DISTANCE = DPIUtil.getWidthByDesignValue720(406) + 500;

    private View followScrollView;
    private int preDistance;
    private SparseIntArray dValues = new SparseIntArray();
    private int totalDy;

    public FollowScrollListener(View followScrollView) {
        this.followScrollView = followScrollView;
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        int distance = Math.max(- MAX_DISTANCE, Math.min(0, getMovedDistance(recyclerView, dy)));

        if (preDistance == distance) return;

        preDistance = distance;

        if (followScrollView != null) {
            followScrollView.setTranslationY(distance);
        }
    }

    /**
     * 解决rv在滑动时item动态变动导致计算滚动总距离有误差的坑:
     * a)上滑时记录各楼层itemView的top位置
     * b) 正常情况下滑动距离与楼层top的差值是不变的。
     * c) 所以下滑时通过(top + 差值)校验获取正确总滚动距离
     * d) 在滑到顶部时清除记录
     * @param recyclerView
     * @param dy
     * @return
     */
    private int getMovedDistance(RecyclerView recyclerView, int dy) {
        totalDy -= dy;

        LinearLayoutManager lm = (LinearLayoutManager) recyclerView.getLayoutManager();
        int position = lm.findFirstVisibleItemPosition();
        View view = lm.findViewByPosition(position);
        if (view == null) return totalDy;
        int top = view.getTop();
        if (dValues.indexOfKey(position) < 0) {
            dValues.put(position, totalDy - top); // a
        } else {
            totalDy = dValues.get(position) + top; // c
        }

        if (Log.D) {
            Log.d("FollowScrollListener", "onScrolled: dy = " + dy + ", totalDy = " + totalDy);
        }

        if (totalDy == 0) {
            dValues.clear(); // d
            if (Log.D) {
                Log.d("FollowScrollListener", "getMovedDistance: dValues cleared");
            }
        }

        return totalDy;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值