HorizontalScrollView within ScrollView Touch Handling

前端 未结 8 1774
轮回少年
轮回少年 2020-11-22 05:28

I have a ScrollView that surrounds my entire layout so that the entire screen is scrollable. The first element I have in this ScrollView is a HorizontalScrollView block tha

8条回答
  •  感情败类
    2020-11-22 05:46

    Update: I figured this out. On my ScrollView, I needed to override the onInterceptTouchEvent method to only intercept the touch event if the Y motion is > the X motion. It seems like the default behavior of a ScrollView is to intercept the touch event whenever there is ANY Y motion. So with the fix, the ScrollView will only intercept the event if the user is deliberately scrolling in the Y direction and in that case pass off the ACTION_CANCEL to the children.

    Here is the code for my Scroll View class that contains the HorizontalScrollView:

    public class CustomScrollView extends ScrollView {
        private GestureDetector mGestureDetector;
    
        public CustomScrollView(Context context, AttributeSet attrs) {
            super(context, attrs);
            mGestureDetector = new GestureDetector(context, new YScrollDetector());
            setFadingEdgeLength(0);
        }
    
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            return super.onInterceptTouchEvent(ev) && mGestureDetector.onTouchEvent(ev);
        }
    
        // Return false if we're scrolling in the x direction  
        class YScrollDetector extends SimpleOnGestureListener {
            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {             
                return Math.abs(distanceY) > Math.abs(distanceX);
            }
        }
    }
    

提交回复
热议问题