是否有任何方法可以更改viewPager的滑动方向。我想在向上滑动时更改片段

时间:2019-06-25 17:24:29

标签: android android-fragments android-viewpager

我想实现在向上/向下滑动时更改片段,但是我在SO上找到的所有解决方案仅适用于RTL,甚至他们只是说要反转列表/片段。我想要一些可靠的方法来实现它。

这些是我尝试过的一些链接:

1)Changing viewPager swipe direction

2)Android change default direction swipe of ViewPager

3)how to make my viewpager swipe from right to left

4)how to reverse the direction of viewPager to left to right order?

5)Swipe Direction in ViewPager

6)Android OnTouch swipe up/down direction change

1 个答案:

答案 0 :(得分:1)

我在大Google海洋的某个地方发现了它。

让我知道它是否对您有帮助。

public class VerticalViewPager extends ViewPager {

    public VerticalViewPager(Context context) {
        this(context, null);
    }

    public VerticalViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    @Override
    public boolean canScrollHorizontally(int direction) {
        return false;
    }

    @Override
    public boolean canScrollVertically(int direction) {
        return super.canScrollHorizontally(direction);
    }

    private void init() {
        setPageTransformer(true, new VerticalPageTransformer());
        setOverScrollMode(View.OVER_SCROLL_NEVER);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        final boolean toIntercept = super.onInterceptTouchEvent(flipXY(ev));
        flipXY(ev);
        return toIntercept;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        final boolean toHandle = super.onTouchEvent(flipXY(ev));
        flipXY(ev);
        return toHandle;
    }

    private MotionEvent flipXY(MotionEvent ev) {
        final float width = getWidth();
        final float height = getHeight();
        final float x = (ev.getY() / height) * width;
        final float y = (ev.getX() / width) * height;
        ev.setLocation(x, y);
        return ev;
    }

    private static final class VerticalPageTransformer implements ViewPager.PageTransformer {
        @Override
        public void transformPage(View view, float position) {
            final int pageWidth = view.getWidth();
            final int pageHeight = view.getHeight();
            if (position < -1) {
                view.setAlpha(0);
            } else if (position <= 1) {
                view.setAlpha(1);
                view.setTranslationX(pageWidth * -position);
                float yPosition = position * pageHeight;
                view.setTranslationY(yPosition);
            } else {
                view.setAlpha(0);
            }
        }
    }
}

与使用ViewPager相同。这会将其从“水平”更改为“垂直”。