import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.OnScrollListener;
import android.view.View;
/**
* RecycleView滚动回调
*/
public abstract class UniqueScrollListenerextends OnScrollListener {
/**
* 防止轻微触屏 影响用户体验
*/
private static final int accidentHeight =120;
/**
* 滚到超过 防止轻微触屏 则回调
*/
private int scrollHeight =1;
/**
* 记录同方向
* 一个方向只回调一次
*/
private boolean isVisible =true;
/**
* 标记开始透明度变化
*/
private boolean startScroll;
/**
* 滚动透明度变化
*/
private float alphaScrollHeight =0f;
/**
* 防止极速滑动到顶部 机率非常小
*/
private int scroll =0;
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (scrollHeight >accidentHeight &&isVisible) {
// 方向:往底部滚动
if (isVisible) {
isVisible =false;
startScroll =true;
scrollHeight =0;
alphaScrollHeight =0;
onBottomDirection();
}
}else if (scrollHeight < -accidentHeight && !isVisible) {
// 方向:往顶部滚动
if (!isVisible) {
isVisible =true;
startScroll =true;
scrollHeight =0;
alphaScrollHeight =50;
onTopDirection();
}
}
if ((isVisible && dy >0) || (!isVisible && dy <0)) {
scrollHeight += dy;
}
if (startScroll) {
alphaScrollHeight += Math.abs(dy);
float alpha =alphaScrollHeight /accidentHeight;
if (isVisible) {
// 显示
float i = alpha *1.25f;
if (i >1) {
startScroll =false;
onScrollAlpha(1);
}else {
onScrollAlpha(i);
}
}else {
// 隐藏
float i =1f - alpha *0.85f;
if (i <0) {
startScroll =false;
onScrollAlpha(0);
}else {
onScrollAlpha(i);
}
}
}
scroll += dy;
if (scroll <0 &&startScroll) {
startScroll =false;
scroll =0;
onScrollAlpha(1);
}
}
/**
* 往顶部滑动回调
*/
public abstract void onTopDirection();
/**
* 往底部滑动回调
*/
public abstract void onBottomDirection();
/**
* 滑动时透明度变化
* view.setAlpha(i);
* view.setVisibility(i == 0 ? View.GONE : View.VISIBLE);
*/
public abstract void onScrollAlpha(float i);
}
网友评论