Android开发经验谈Android开发沉淀Android开发

item高度不同时Recyclerview获取滑动距离

2018-11-08  本文已影响17人  MingMing很忙

前言

最近遇到需求,要计算RecyclerView滑动距离,用提供的computeVerticalScrollOffset()方法得到的值不是很准确。是基于item的平均高度算得,如果列表中item高度一致可以用此方法。问题来了,我的应用场景是各item高度不一,这时就只能另找方法了。

private int totalDy = 0;
mRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrolled(RecyclerView recyclerview, int dx, int dy) {
        totalDy -= dy;
    }
}

1.统计列表已展示过的item的高度,在每次布局完成的时候,用一个map记录positon位置item对应的view的高度。

private Map<Integer, Integer> heightMap = new HashMap<>();
int count = getChildCount();
for (int i = 0; i < count; i++) {
    View view = getChildAt(i);
    heightMap.put(i, view.getHeight());
}

2.重写computeVerticalScrollOffset(),找到当前屏幕第一个可见item的position,通过heightMap循环累加0到positon的item高度,再加上第一个可见item不可见部分高度。最终得到整个列表的滑动偏移。

@Override
public int computeVerticalScrollOffset(RecyclerView.State state) {
    if (getChildCount() == 0) {
        return 0;
    }
    int firstVisiablePosition = findFirstVisibleItemPosition();
    View firstVisiableView = findViewByPosition(firstVisiablePosition);
    int offsetY = -(int) (firstVisiableView.getY());
    for (int i = 0; i < firstVisiablePosition; i++) {
        offsetY += heightMap.get(i) == null ? 0 : heightMap.get(i);
    }
    return offsetY;
}

3.最终代码

public class OffsetLinearLayoutManager extends LinearLayoutManager {

    public OffsetLinearLayoutManager(Context context) {
        super(context);
    }

    private Map<Integer, Integer> heightMap = new HashMap<>();

    @Override
    public void onLayoutCompleted(RecyclerView.State state) {
        super.onLayoutCompleted(state);
        int count = getChildCount();
        for (int i = 0; i < count ; i++) {
            View view = getChildAt(i);
            heightMap.put(i, view.getHeight());
        }
    }

    @Override
    public int computeVerticalScrollOffset(RecyclerView.State state) {
        if (getChildCount() == 0) {
            return 0;
        }
        try {
            int firstVisiablePosition = findFirstVisibleItemPosition();
            View firstVisiableView = findViewByPosition(firstVisiablePosition);
            int offsetY = -(int) (firstVisiableView.getY());
            for (int i = 0; i < firstVisiablePosition; i++) {
                offsetY += heightMap.get(i) == null ? 0 : heightMap.get(i);
            }
            return offsetY;
        } catch (Exception e) {
            return 0;
        }
    }
}

mRecycler.setLayoutManager(new OffsetLinearLayoutManager(mContext));
上一篇下一篇

猜你喜欢

热点阅读