android: ViewPager and HorizontalScrollVIew

Android Noob picture Android Noob · Aug 3, 2011 · Viewed 36k times · Source

I have a HorizontalScrollView inside my ViewPager. I set requestDisallowInterceptTouchEvent(true); for the HorizontalScrollView but the ViewPager is still sometimes intercepting touch events. Is there another command I can use to prevent a View's parent and ancestors from intercepting touch events?

note: the HorizontalScrollView only occupies half the screen.

Answer

Fede picture Fede · Aug 31, 2011

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