ScrollView inside Gallery, both scrolling independently

前端 未结 2 1261
说谎
说谎 2020-12-09 00:46

I have a Gallery with an adapter which supplies it ScrollViews as its child views. I need to make sure that the touch events are handled correctly and as expected:

2条回答
  •  猫巷女王i
    2020-12-09 01:27

    OK, after some major fiddling and logcat hacking, here's the solution:

    public class SwipeInterceptingGallery extends Gallery {
    
        private float mInitialX;
        private float mInitialY;
        private boolean mNeedToRebase;
        private boolean mIgnore;
    
        public SwipeInterceptingGallery(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }
    
        public SwipeInterceptingGallery(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public SwipeInterceptingGallery(Context context) {
            super(context);
        }
    
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
                float distanceY) {
            if (mNeedToRebase) {
                mNeedToRebase = false;
                distanceX = 0;
            }
            return super.onScroll(e1, e2, distanceX, distanceY);
        }
    
        @Override
        public boolean onInterceptTouchEvent(MotionEvent e) {
            switch (e.getAction()) {
                case MotionEvent.ACTION_DOWN: {
                    mIgnore = false;
                    mNeedToRebase = true;
                    mInitialX = e.getX();
                    mInitialY = e.getY();
                    return false;
                }
    
                case MotionEvent.ACTION_MOVE: {
                    if (!mIgnore) {
                        float deltaX = Math.abs(e.getX() - mInitialX);
                        float deltaY = Math.abs(e.getY() - mInitialY);
                        mIgnore = deltaX < deltaY;
                        return !mIgnore;
                    }
                    return false;
                }
                default: {
                    return super.onInterceptTouchEvent(e);
                }
            }
        }
    }
    

提交回复
热议问题