android: ViewPager and HorizontalScrollVIew

I had the same problem. My solution was:

  1. Make a subclass of ViewPager and add a property called childId.
  2. Create a setter for the childId property and set the id of the HorizontalScrollView.
  3. Override onInterceptTouchEvent() in the subclass of ViewPager and if the childId property is more than 0 get that child and if the event is in HorizontalScrollView area return false.

Code

public class CustomViewPager extends ViewPager {

    private int childId;    

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

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        if (childId > 0) {
            View scroll = findViewById(childId);
            if (scroll != null) {
                Rect rect = new Rect();
                scroll.getHitRect(rect);
                if (rect.contains((int) event.getX(), (int) event.getY())) {
                    return false;
                }
            }
        }
        return super.onInterceptTouchEvent(event);
    }

    public void setChildId(int id) {
        this.childId = id;
    }
}

In onCreate() method

viewPager.setChildId(R.id.horizontalScrollViewId);
adapter = new ViewPagerAdapter(this);
viewPager.setAdapter(adapter);

Hope this help

Leave a Comment