简体   繁体   English

当父卷轴滚动时,Android View停止接收触摸事件

[英]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. 我有一个自定义的Android视图,它覆盖了onTouchEvent(MotionEvent)来处理视图中内容的水平滚动。 However, when the ScrollView in which this is contained scrolls vertically, the custom view stops receiving touch events. 但是,当包含它的ScrollView垂直滚动时,自定义视图会停止接收触摸事件。 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. 在子视图中使用requestDisallowInterceptTouchEvent(true)以防止垂直滚动(如果要继续进行水平滚动,并在完成后重置它)。

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 :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). 此问题的解决方法是扩展ScrollView并覆盖onInterceptTouchEvent方法,以便它只截取Y移动很重要的触摸事件(根据一个建议,大于X移动)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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