Search code examples
androideventstouchandroid-scrollview

How to transfer touch events to the view beneath in a RelativeLayout?


I have a ScrollView on top of another view(with Buttons). The ScrollView is taking the whole screen and is obscuring the view that is beneath it.

At some point in my app I need the ScrollView to be disabled (but still visible) and transfer all the touch events to the Buttons that are beneath the ScrollView. How can I do that? Some views like Buttons are automatically doing that when disabled but a ScrollView is not doing that.


Solution

  • Try to implement your own ScrollView which has a flag to indicate the status(disabled/enabled) and also overrides the onTouchEvent and dispatchTouchEvent to let the touch events get pass the ScrollView. Here is an example:

    public class DisabledScrollView extends ScrollView {
    
        private boolean mIsDisable = false;
    
        // if status is true, disable the ScrollView
        public void setDisableStatus(boolean status) {
            mIsDisable = status;
        }
    
        @Override
        public boolean onTouchEvent(MotionEvent ev) {
            // no more tocuh events for this ScrollView
            if (mIsDisable) {
                return false;
            }       
            return super.onTouchEvent(ev);
        }
    
        public boolean dispatchTouchEvent(MotionEvent ev) {
            // although the ScrollView doesn't get touch events , its children will get them so intercept them.
            if (mIsDisable) {
                return false;
            }
            return super.dispatchTouchEvent(ev);
        }
    
    }
    

    Then all you have to do is change the value of that flag. See if it works.