I have a LinearLayout inside a HorizontalScrollView. The content is just a image. While scrolling, I need to achieve the same behavior you get when setting the paging option on a the iPhone equivalent of the HSW (scrolling the list should stop at every page on the list, not continue moving).
How is this done in Android? Should I implement this features by myself or there is a particular property to set or a subclass of HSV to implement?
The android. widget. HorizontalScrollView class provides the functionality of horizontal scroll view. HorizontalScrollView is used to scroll the child elements or views in a horizontal direction.
ScrollView and HorizontalScrollView has same attributes, the only difference is scrollView scroll the child items in vertical direction while horizontal scroll view scroll the child items in horizontal direction.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In this above code, we have declare Linear layout as parent and added Vertical Scroll view.
I came across a nice solution here:
Horizontal Pager
this is a cleaned up GitHub version of the code found here:
Real View Switcher
It may seem like overkill for just using it on images, but this solution allows for infinite paging with using a little trick (ie: when on first page you can scroll back to last page and when on last page you can scroll forward to first page). It also allows you to have an unknown number of pages and dynamically generate content by using another little trick. Please see my comment in the second link here
for details on how i accomplished this.
Hope this helps.
So, my solution is:
The method computeScroll the called to move the list. By default I suppose it's implemented to decelerate with a certain ratio... Since I don't want this motion, I just override it without specifing a body.
The code for the event handler is:
_scrollView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if(event.getAction() == MotionEvent.ACTION_UP) { float currentPosition = _scrollView.getScrollX(); float pagesCount = _horizontalBar.getChildCount(); float pageLengthInPx = _horizontalBar.getMeasuredWidth()/pagesCount; float currentPage = currentPosition/pageLengthInPx; Boolean isBehindHalfScreen = currentPage-(int)currentPage > 0.5; float edgePosition = 0; if(isBehindHalfScreen) { edgePosition = (int)(currentPage+1)*pageLengthInPx; } else { edgePosition = (int)currentPage*pageLengthInPx; } _scrollView.scrollTo((int)edgePosition, 0); } return false; } });
And in my inherited HorizontalScrollView
@Override public void computeScroll (){ return; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With