import androidx.viewpager2.widget.ViewPager2;
import com.aiyiqi.base.util.LogUtil;
import java.util.function.BiConsumer;
public class CustomOnPageChangeCallback extends ViewPager2.OnPageChangeCallback {
/**
* 页面位置偏移回调
* Boolean 当前滑动页面是和上次滑动页面是否是同一页面 默认滑初始动页面是 0
* Integer 滑动偏移量 范围 0-1
**/
private BiConsumer<Boolean, Float> pageScrolledCallback;
public CustomOnPageChangeCallback(BiConsumer<Boolean, Float> pageScrolledCallback) {
this.pageScrolledCallback = pageScrolledCallback;
}
/**
* 上次滑动的页面
**/
private int previousPosition = 0;
/**
* 当前ViewPager2选中的页面
**/
private int currentPosition = 0;
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
boolean b = false;
if (position == previousPosition) {
b = true;
} else if (position < previousPosition) {
b = false;
}
if (pageScrolledCallback != null && positionOffset > 0) {
pageScrolledCallback.accept(b, positionOffset);
}
}
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
// 记录当选择新页面时。
currentPosition = position;
}
@Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
if (state == ViewPager2.SCROLL_STATE_IDLE) {
// 滑动结束
previousPosition = currentPosition;
}
}
}
网友评论