RecyclerView监听滑动距离

需求:RecyclerView中实现往上滑动背景颜色或者图片变淡直至白色或者透明,往下滑背景颜色或者图片从白色逐渐变成正常颜色

图示:
device-2020-03-27-154834.png

下滑的时候


device-2020-03-27-154853.png

常见思路做法:
int totalScrollY;

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}

        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            totalScrollY += dy;
            if (totalScrollY <= 0) {
                bgView.getBackground().mutate().setAlpha(255);
            } else if (totalScrollY <= 120) {
                bgView.getBackground().mutate().setAlpha((int) (255f - 255.0f / 120 * totalScrollY));
            } else {
                bgView.getBackground().mutate().setAlpha(0);
            }
        }
    });

利用onScrolled里面的dy值来进行RecyclerView在y方向上面的滑动距离统计,然后根据滑动距离进行view的变化。

大部分的情况下该种做法是没有问题。不过在很极端的情况下会出现totalScrollY的值不准确的问题。

换种做法,totalScrollY不是通过累加dy来计算(注意:下面这种做法只适用于item的高度是固定统一的情况)

private int getScrollYDistance() {
try {
GridLayoutManager layoutManager = (GridLayoutManager) iRecyclerView.getLayoutManager();
if (layoutManager != null) {
int position = layoutManager.findFirstVisibleItemPosition();
View firstVisibleChildView = layoutManager.findViewByPosition(position);
if (firstVisibleChildView != null) {
int itemHeight = firstVisibleChildView.getHeight();
return position* itemHeight - firstVisibleChildView.getTop();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}

你可能感兴趣的:(RecyclerView监听滑动距离)