Search code examples
androidontouchlistenerandroid-scrollviewontouchonscrolllistener

Android disable child onTouch when ScrollView scrolls


On my layout, I have a ScrollView which hosts a VideoView and other TextViews.

My VideoView has a onTouch listener to start playing the video:

viPlayer.setOnTouchListener(new OnTouchListener() {
      @Override
      public boolean onTouch(View v, MotionEvent event) {
         if (isPlaying) {
            isPlaying = false;
            viPlayer.stopPlayback();
         } else {
            isPlaying = true;
            viPlayer.start();
         }
         return false;
      }
});

The problem I am facing is this: when the user puts the finger above the VideoView and starts to scroll down the ScrollView, the video starts to play. I want that when a Scroll is performed, the child views of ScrollView should not do anything. I see there is no listener for onScroll for ScrollView. How can I fix this?


Solution

  • UPDATE Let me explain you what was happening. The child's touch events are always called first and only after the parent's event is called. What you are trying to do it's hard without some hacks. When you first touch on the video it's touch event is called and after that the scrollview's event is called. How can the video view know if you are going to scroll or not? It doesn't know upfront what you're trying to do. So how can you know if you should play or not the video?

    So I tested this and this is working for me. Change your video touchevent to this. Remove the scrollview touch event. Notice the return true instead of return false.

            @Override
            public boolean onTouch(View view, MotionEvent motionEvent)
            {
                switch (motionEvent.getAction()){
                    case MotionEvent.ACTION_UP:
                        if (isPlaying) {
                         isPlaying = false;
                         viPlayer.stopPlayback();
                        } else {
                         isPlaying = true;
                         viPlayer.start();
                        }
                        break;
                }
                return true;
            }