简体   繁体   中英

Android View stops receiving touch events when parent scrolls

I have a custom Android view which overrides onTouchEvent(MotionEvent) to handle horizontal scrolling of content within the view. However, when the ScrollView in which this is contained scrolls vertically, the custom view stops receiving touch events. Ideally what I want is for the custom view to continue receiving events so it can handle its own horizontal scrolling, while the containing view hierarchy deals with vertical scrolling.

Is there any way to continue receiving those motion events on scroll? If not, is there any other way to get the touch events I need?

Use requestDisallowInterceptTouchEvent(true) in the childview to prevent from vertical scrolling if you want to continue doing horizontal scrolling and latter reset it when done.

private float downXpos = 0;
private float downYpos = 0;
private boolean touchcaptured = false;
@Override
public boolean onTouchEvent(MotionEvent event) {
    switch(event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        downXpos = event.getX();
        downYpos = event.getY();
        touchcaptured = false;
        break;
    case MotionEvent.ACTION_UP:
        requestDisallowInterceptTouchEvent(false);
        break;
    case MotionEvent.ACTION_MOVE:
        float xdisplacement = Math.abs(event.getX() - downXpos);
        float ydisplacement = Math.abs(event.getY() - downYpos);
        if( !touchcaptured && xdisplacement > ydisplacement && xdisplacement > 10) {
            requestDisallowInterceptTouchEvent(true);
            touchcaptured = true;
        }
        break;
    }
    super.onTouchEvent(event);
    return true;
}

I'm answering my own question in case anyone else is as bad at Googling for the answer as I apparently was. :P

A workaround for this problem is to extend ScrollView and override the onInterceptTouchEvent method so that it only intercepts touch events where the Y movement is significant (greater than the X movement, according to one suggestion).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM