需求:RecyclerView中實現(xiàn)往上滑動背景顏色或者圖片變淡直至白色或者透明斩启,往下滑背景顏色或者圖片從白色逐漸變成正常顏色
圖示:下滑的時候
常見思路做法:
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方向上面的滑動距離統(tǒng)計豪嚎,然后根據(jù)滑動距離進行view的變化浑测。
大部分的情況下該種做法是沒有問題。不過在很極端的情況下會出現(xiàn)totalScrollY的值不準確的問題妄呕。
換種做法领曼,totalScrollY不是通過累加dy來計算(注意:下面這種做法只適用于item的高度是固定統(tǒng)一的情況)
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;
}