美文网首页
CustomOnPageChangeCallback

CustomOnPageChangeCallback

作者: 天堂守望者 | 来源:发表于2023-07-14 00:55 被阅读0次
    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;
            }
        }
    }
    
    

    相关文章

      网友评论

          本文标题:CustomOnPageChangeCallback

          本文链接:https://www.haomeiwen.com/subject/ydjvudtx.html