Skip to content
Advertisement

Snapping Effect in HorizontalScrollView

I want to achieve Snapping effect in HorizontalScrollView i.e when the user scrolls horizontally the item which is most visible (item visible > 50%) comes to the center.

I tried to do this using:

JavaScript

But the value is not constant even when we do not touch the screen.

Here is some part of logcat:

JavaScript

I’ve already tried these solutions, either I am not getting the point or I don't know to do it:

  1. HorizontalScrollView within ScrollView Touch Handling
  2. HorizontalScrollView with snapping effect
  3. Creating Custom Horizontal Scroll View With Snap or paging
  4. Creating a “Snapping” Horizontal Scroll View

My Usecase: I have an HorizontalScrollView which is attached to the adapter of Recyclerview(Vertical) so snapHelper can be done in vertical but I don’t know how to make it for horizontal.

Advertisement

Answer

Here is a complete code for a Custom Horizontal Scroll View that snaps the items.

JavaScript

This example does adding the views programatically and calls them Features. But you can simple change that behaviour and use getChildrenCount() instead of mItems.size() and so on.

The important part is the GestureDetector and TouchListener. In TouchListener, you can listen for ACTION_UP which is when the user’s finger is removed (like after scroll) and you calculate which view is the active one based on the amount of scroll and their positions. You can also add a GestureDetector to catch the fling operations and do the same there.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement