Search code examples
javaandroidviewgroup

Prevent parent from getting touch events only for certain views?


I have a ScrollView and linear layout inside it. Inside the linear layout i have multiple views. One of the multiple views (DrawView lets say)is used to draw stuff so i have to override onTouchEvent of that method and draw things. Currently when i drag or move on the DrawView, the ScrollView also handles the touch leading the entire view moving. What i want is that when i touch the DrawView , the scroll view should not move . I went through some of these answers here

How to vary between child and parent view group touch events

but i did not find anything that i can add in DrawView which will prevent the ScrollView from moving up and down. Note that DrawView does not extend ViewGroup so i don't have access to requestDisallowInterceptTouchEvent


Solution

  • You can get the ScrollView from your DrawView's onTouchEvent:

    ScrollView scrollView = (ScrollView) getParent();
    

    then you can call requestDisallowInterceptTouchEvent on scrollView to prevent it from scrolling when you touch the DrawView.

    scrollView.requestDisallowInterceptTouchEvent(true);