How to consume child view's touch event in parent view's touchlistener?

前端 未结 4 1016
慢半拍i
慢半拍i 2020-12-29 06:59

In my application I want to get the touch event of all child view\'s in my parent view\'s onTouchListener but I could not get this.

Example:

相关标签:
4条回答
  • 2020-12-29 07:35

    2 solutions:

    1. Use onInterceptTouchEvent on the ViewGroup, as shown here

    2. Avoid having the layout handle the touch events, and have a view that is the child view of the layout, that covers its whole size, to handle the touch events.

      It's not as efficient as extending classes, but it is much easier and doesn't require to create new files/classes.

      example:

      Just add the touch events to the view, and it will handle them instead of any of the other views.

    0 讨论(0)
  • 2020-12-29 07:35

    It can be achieved by using "onInterceptTouchEvent". Please try this,it may work

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
         onTouchEvent(ev);
         return  false;
    }
    
    0 讨论(0)
  • 2020-12-29 07:43

    I have tried similar design with (only one onTouch Listener on a root FrameLayout) and it worked. I get all the points provided that onTouch return true instead of false. Otherwise, I just get the first point. I couldn't find out the reason for this "return" issue since I expect opposite behaviour.

    However, based on my experience, if you set any of child view clickable, then its parent's onTouch will not work. If you have another solution and if you share, that would be great.

    0 讨论(0)
  • 2020-12-29 07:46

    You could accomplish that by overriding dispatchTouchEvent in the layout.

    public class MyFrameLayout extends FrameLayout {
        @Override
        public boolean dispatchTouchEvent(MotionEvent e) {
            // do what you need to with the event, and then...
            return super.dispatchTouchEvent(e);
        }
    }
    

    Then use that layout in place of the usual FrameLayout:

    <com.example.android.MyFrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="10dip"
        android:id="@+id/rootview">
      ...
    

    You could also skip the super call entirely if you need to prevent child views from receiving the event, but I think this would be rare. If you need to recreate some, but not all, of the default functionality, there is a lot to rewrite:

    http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.1.1_r1/android/view/ViewGroup.java#ViewGroup.dispatchTouchEvent%28android.view.MotionEvent%29

    0 讨论(0)
提交回复
热议问题