Horizontal ScrollView paginated

I want to make a horizontal scrollview paginated. If you move the screen to the right, then it will display the desired “page”, and if you move the screen to the left, it will display the left “page”.

+3
source share
1 answer

I have done this in the past. You can do this with a custom listener:

public MyHorizontalScrollView(Context context, AttributeSet attrs) {
    super(context, attrs);
    setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL ){
                    int scrollX = getScrollX();
                    int itemWidth = getMeasuredWidth();
                    int activeItem = ((scrollX + itemWidth / 2) / itemWidth);
                    int scrollTo = activeItem * itemWidth;
                    smoothScrollTo(scrollTo, 0);

                    return true;
                } else {
                    return false;
                }
            }
        });
    }

Pretty clear, I think. This assumes that the width of your pages is constant and equal to the width of the entire scroll.

+12
source

All Articles