HorizontalVerticalViewPager实现水平垂

作者: Android高级开发 | 来源:发表于2019-04-25 16:34 被阅读9次

    水平垂直都可滑动的HorizontalVerticalViewPager实现

    自定义一个可以在垂直方向上滑动的ViewPager,同时支持水平和垂直方向手动切换和自动切换(根据手势判断),垂直方向的实现通过PageTransformer来完成,自动切换功能则涉及到手势的相关内容。以下是内容简介:

    • 垂直滑动的ViewPager实现思路

    • PageTransformer的使用

    • 手势事件的分发和处理

    垂直滑动的ViewPager实现思路

    Android的兼容包support-v4提供的ViewPager默认是水平滑动切换的,但是,想要实现垂直滑动,可行的方案还是不少的,下面举几个例子:

    • 直接拷贝ViewPager源码,把所有涉及到的水平控制的参数,调整为垂直;

    • 旋转ViewPager的item的角度;

    • 设置页面切换动画PageTransformer;

    当然,还有很多其他的方式来实现,我这里使用的就是比较简单的PageTransformer,简单,是因为只需要给水平的ViewPager设置一个PageTransformer就能实现,不用自定义ViewPager。

    PageTransformer的使用

    关于PageTransformer首先要知道的是,这是一个控制ViewPager页面滑动动画的一个类,要给页面设置各种滑入和滑出的动画,需要实现PageTransformer接口,实现里面的transformPage(View page,int position)方法,做动画相关的操作。

    先来看看官方的Demo:

    Picture

    对应的代码如下:

    public class DepthPageTransformer implements ViewPager.PageTransformer {
        private static final float MIN_SCALE = 0.75f;
    
        public void transformPage(View view, float position) {
            int pageWidth = view.getWidth();
    
            if (position < -1) { // [-Infinity,-1)
                // This page is way off-screen to the left.
                view.setAlpha(0);
    
            } else if (position <= 0) { // [-1,0]
                // Use the default slide transition when moving to the left page
                view.setAlpha(1);
                view.setTranslationX(0);
                view.setScaleX(1);
                view.setScaleY(1);
    
            } else if (position <= 1) { // (0,1]
                // Fade the page out.
                view.setAlpha(1 - position);
    
                // Counteract the default slide transition
                view.setTranslationX(pageWidth * -position);
    
                // Scale the page down (between MIN_SCALE and 1)
                float scaleFactor = MIN_SCALE
                        + (1 - MIN_SCALE) * (1 - Math.abs(position));
                view.setScaleX(scaleFactor);
                view.setScaleY(scaleFactor);
    
            } else { // (1,+Infinity]
                // This page is way off-screen to the right.
                view.setAlpha(0);
            }
        }
    }
    
    Picture

    对应的PageTransformer实现:

    public class ZoomOutPageTransformer implements ViewPager.PageTransformer {
        private static final float MIN_SCALE = 0.85f;
        private static final float MIN_ALPHA = 0.5f;
    
        public void transformPage(View view, float position) {
            int pageWidth = view.getWidth();
            int pageHeight = view.getHeight();
    
            if (position < -1) { // [-Infinity,-1)
                // This page is way off-screen to the left.
                view.setAlpha(0);
    
            } else if (position <= 1) { // [-1,1]
                // Modify the default slide transition to shrink the page as well
                float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
                float vertMargin = pageHeight * (1 - scaleFactor) / 2;
                float horzMargin = pageWidth * (1 - scaleFactor) / 2;
                if (position < 0) {
                    view.setTranslationX(horzMargin - vertMargin / 2);
                } else {
                    view.setTranslationX(-horzMargin + vertMargin / 2);
                }
    
                // Scale the page down (between MIN_SCALE and 1)
                view.setScaleX(scaleFactor);
                view.setScaleY(scaleFactor);
    
                // Fade the page relative to its size.
                view.setAlpha(MIN_ALPHA +
                        (scaleFactor - MIN_SCALE) /
                        (1 - MIN_SCALE) * (1 - MIN_ALPHA));
    
            } else { // (1,+Infinity]
                // This page is way off-screen to the right.
                view.setAlpha(0);
            }
        }
    }
    

    关于Demo的具体解读,参见官网示例
    下面是垂直滑动效果:

    Picture

    对应的PageTransformer实现:

    private class VerticalPageTransformer implements ViewPager.PageTransformer {  
    
            @Override  
            public void transformPage(View view, float position) {  
    
                if (position < -1) { // [-Infinity,-1)  
                    // This page is way off-screen to the left.  
                    view.setAlpha(0);  
    
                } else if (position <= 1) { // [-1,1]  
                    view.setAlpha(1);  
    
                    // Counteract the default slide transition  
                    view.setTranslationX(view.getWidth() * -position);  
    
                    //set Y position to swipe in from top  
                    float yPosition = position * view.getHeight();  
                    view.setTranslationY(yPosition);  
    
                } else { // (1,+Infinity]  
                    // This page is way off-screen to the right.  
                    view.setAlpha(0);  
                }  
            }  
        } 
    

    到这里其实就已经可以上下滑动了,但是手势却还是左右滑动,还需要再做一点改动。把左右滑动的手势变换为上下滑动。

       /**
        * Swaps the X and Y coordinates of your touch event.
        */
        private MotionEvent swapXY(MotionEvent ev) {
            float width = getWidth();
            float height = getHeight();
    
            float newX = (ev.getY() / height) * width;
            float newY = (ev.getX() / width) * height;
    
            ev.setLocation(newX, newY);
    
            return ev;
        }
    
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (isVertical) {
                boolean intercepted = super.onInterceptTouchEvent(swapXY(ev));
                swapXY(ev); // return touch coordinates to original reference frame for any child views
                return intercepted;
            } else {
                return super.onInterceptTouchEvent(ev);
            }
        }
    
        @Override
        public boolean onTouchEvent(MotionEvent ev) {
            if (isVertical) {
                return super.onTouchEvent(swapXY(ev));
            } else {
                return super.onTouchEvent(ev);
            }
        }
    

    效果如下:

    Picture

    到这里,一个垂直滚动的ViewPager已经实现了。

    记住,别忘了把实现的PageTransformer设置给ViewPager:

    setPageTransformer(true, new HorizontalVerticalPageTransformer());
    

    关于PageTransformer更多的内容,还可以看看CSDN博客专家们的解读:

    巧用ViewPager 打造不一样的广告轮播切换效果
    PageTransformer实现个性的ViewPager切换动画

    手势事件的分发和处理

    现在,我要做的是,既可以水平滑动又可以垂直滑动,完全根据手指滑动的方向自动的切换滑动方向,通过按钮手动切换的这里就不细说了,相信看完自动切换的细节,手动的也就不是什么问题了。

    这里的手势,监听的是ViewPager的item里面的ImageView控件的,所以,实现一个OnGestureListener,然后,在ImageView的touch事件交给GestureDetector来处理,看看OnGestureListener的代码:

    private class GestureListener implements GestureDetector.OnGestureListener {
    
            @Override
            public boolean onDown(MotionEvent e) {
                Log.i(getClass().getName(), "onDown-----" + getActionName(e.getAction()));
                return false;
            }
    
            @Override
            public void onShowPress(MotionEvent e) {
                Log.i(getClass().getName(), "onShowPress-----" + getActionName(e.getAction()));
            }
    
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                Log.i(getClass().getName(), "onSingleTapUp-----" + getActionName(e.getAction()));
                return false;
            }
    
            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                Log.i(getClass().getName(), "onScroll-----"
                        + getActionName(e2.getAction()) + ",(" + e1.getX() + "," + e1.getY() + ") ,("
                        + e2.getX() + "," + e2.getY() + ")");
                return false;
            }
    
            @Override
            public void onLongPress(MotionEvent e) {
                Log.i(getClass().getName(), "onLongPress-----" + getActionName(e.getAction()));
            }
    
            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                Log.i(getClass().getName(),
                        "onFling-----" + getActionName(e2.getAction()) + ",(" + e1.getX() + "," + e1.getY() + ") ,("
                                + e2.getX() + "," + e2.getY() + ")");
    
                float detly_x = e1.getX() - e2.getX();
                float detly_y = e1.getY() - e2.getY();
    
                if (Math.abs(detly_x) > Math.abs(detly_y)) {// 水平方向滑动
                    int offsetPosition = 0;
                    if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE) {
                        offsetPosition = 1;
                        Log.i(getClass().getName(), "onFling----- 向左滑动");
                    } else if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE) {
                        offsetPosition = -1;
                        Log.i(getClass().getName(), "onFling----- 向右滑动");
                    }
                    mOnTouchListener.onHorizontalFling(offsetPosition);
                } else {// 垂直方向滑动
                    int offsetPosition = 0;
                    if (e1.getY() - e2.getY() > FLING_MIN_DISTANCE) {
                        offsetPosition = 1;
                        Log.i(getClass().getName(), "onFling----- 向上滑动");
                    } else if (e2.getY() - e1.getY() > FLING_MIN_DISTANCE) {
                        offsetPosition = -1;
                        Log.i(getClass().getName(), "onFling----- 向下滑动");
                    }
                    mOnTouchListener.onVerticalFling(offsetPosition);
                }
    
                return false;
            }
    
            private String getActionName(int action) {
                String name = "";
                switch (action) {
                    case MotionEvent.ACTION_DOWN: {
                        name = "ACTION_DOWN";
                        break;
                    }
                    case MotionEvent.ACTION_MOVE: {
                        name = "ACTION_MOVE";
                        break;
                    }
                    case MotionEvent.ACTION_UP: {
                        name = "ACTION_UP";
                        break;
                    }
                    default:
                        break;
                }
                return name;
            }
        }
    

    设置给ImageView:

    final GestureDetector detector = new GestureDetector(context, new GestureListener());
            iv.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    detector.onTouchEvent(event);
                    return true;
                }
            });
    

    当然,PageTransformer也要进行改造:

    private class HorizontalVerticalPageTransformer implements PageTransformer {
    
            private static final float MIN_SCALE = 0.75f;
    
            @Override
            public void transformPage(View page, float position) {
                if (isVertical) {
    
                    if (position < -1) {
                        page.setAlpha(0);
                    } else if (position <= 1) {
                        page.setAlpha(1);
    
                        // Counteract the default slide transition
                        float xPosition = page.getWidth() * -position;
                        page.setTranslationX(xPosition);
    
                        //set Y position to swipe in from top
                        float yPosition = position * page.getHeight();
                        page.setTranslationY(yPosition);
                    } else {
                        page.setAlpha(0);
                    }
                } else {
                    int pageWidth = page.getWidth();
    
                    if (position < -1) { // [-Infinity,-1)
                        // This page is way off-screen to the left.
                        page.setAlpha(0);
    
                    } else if (position <= 0) { // [-1,0]
                        // Use the default slide transition when moving to the left page
                        page.setAlpha(1);
                        page.setTranslationX(0);
                        page.setScaleX(1);
                        page.setScaleY(1);
    
                    } else if (position <= 1) { // (0,1]
                        // Fade the page out.
                        page.setAlpha(1 - position);
    
                        // Counteract the default slide transition
                        page.setTranslationX(pageWidth * -position);
                        page.setTranslationY(0);
    
                        // Scale the page down (between MIN_SCALE and 1)
                        float scaleFactor = MIN_SCALE
                                + (1 - MIN_SCALE) * (1 - Math.abs(position));
                        page.setScaleX(scaleFactor);
                        page.setScaleY(scaleFactor);
    
                    } else { // (1,+Infinity]
                        // This page is way off-screen to the right.
                        page.setAlpha(0);
                    }
                }
            }
        }
    

    再看看效果是怎么样的吧:

    Picture

    相关文章

      网友评论

        本文标题:HorizontalVerticalViewPager实现水平垂

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