How to smooth the vertical viewpager in android

2.2k views Asked by At

Im creating one application, so i used vertical viewpager, viewpager working fine but it is not scrolling smoothly, it is sticking sometimes while swipe. here is my code, can anyone help me.thanks in advance.

 public class VerticalViewPager extends ViewPager {
public VerticalViewPager(Context context) {
    super(context);
    init();
}

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

private void init() {
    // The majority of the magic happens here
    setPageTransformer(true, new VerticalPageTransformer());
    // The easiest way to get rid of the overscroll drawing that happens on the left and right
    setOverScrollMode(OVER_SCROLL_NEVER);
}


private static class VerticalPageTransformer implements PageTransformer {
    private static float MIN_SCALE = 0.95f;

    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 <= 0) { // [-1,0]

            view.setAlpha(1);
            //view.setTranslationX(1);
            view.setScaleX(1);
            view.setScaleY(1);
            float yPosition = position * view.getHeight();
            view.setTranslationY(yPosition);
            view.setTranslationX(-1 * view.getWidth() * position);

        } else if (position <= 1) { // (0,1]
            // Fade the page out.
            view.setAlpha(1 - position);

            view.setTranslationX(-1 * view.getWidth() * 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 {
            view.setAlpha(0);
        }

    }
}

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) {
    boolean intercepted = super.onInterceptTouchEvent(swapXY(ev));
    swapXY(ev);
    return intercepted;
}

@Override
public boolean onTouchEvent(MotionEvent ev) {
    return super.onTouchEvent(swapXY(ev));
}
2

There are 2 answers

0
Tejas Dhawale On

I had the same issue with vertical viewpager. Finally, I got solution by just adding this attribute:

android:clickable="false"

in viewpager adapter's item view. So add it in on views (i.e imageview and textview depends on your layout) which don't have any onClick function with it.

0
oferiko On

yes, all you need to do is ad this line to the view pager class:

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