Alex
Alex

Reputation: 7057

HorizontalScrollView paginated

I want to do a HorizontalScrollView paginated. If you move the screen to right, then it would show the right "page" and if you move the screen to left, then it would show the left "page".

Upvotes: 3

Views: 2414

Answers (1)

alex.zherdev
alex.zherdev

Reputation: 24164

I've done this thing in the past. You can do this via a custom touch 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 self-explanatory, I think. This assumes that the width of your pages is constant and equal to the width of the whole scrollview.

Upvotes: 14

Related Questions