I have a one RelativeLayout
and this layout is having nearly 10 views in it.
I have set OnTouchListener
to this Layout and doing some work in it and returning true
.
this listener is working fine when I touch the layout where there are no View (mean on Empty area). If I touch on child views of this layout, this listener is not firing...
and from the documentation, I understood that we can override onInterceptTouchEvent()
by extending ViewGroup (so here RelativeLayout) and handle touch events before child views consume this event...
this will do a trick, but I need to modify many xml files where I need this functionality by replacing RelativeLayout with my CustomRelativeLayout.
so my question is:
is there any way to handle touch event for RelativeLayout
(ofcourse ViewGroup) before child views in RelativeLayout
consumes event? I don't want to extend RelativeLayout
...
To make sure that each view correctly receives the touch events intended for it, override the onInterceptTouchEvent() method.
1.1. You can react to touch events in your custom views and your activities. Android supports multiple pointers, e.g. fingers which are interacting with the screen. The base class for touch support is the MotionEvent class which is passed to Views via the onTouchEvent() method. you override the onTouchEvent() method.
 Gestures are scripted “solutions” that take advantage of these touch events.  So instead of tracking two touch points to determine if they're moving away or closer to one another in order to manipulate the size of a photo, you can just use GESTURE_ZOOM.
If you return false than the touch event will be passed to the next View further up in the view hierarchy and you will receive no follow up calls. The touch event will continue to be passed further up the view hierarchy until someone consumes it.
Try to override
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
return super.dispatchTouchEvent(ev);
}
of Activity
.
This method is the first that process touch events.
But in this case you need to work with current coordinates of views
While not necessarily being ideal, this works well for smaller layouts that won't have dynamic content.
In xml, set android:clickable="false"
to all descendants of the ViewGroup in the layout (including nested ViewGroups and their children). Each child that gets clicked on will then propagate the click to its parent, eventually getting to the ViewGroup's default touch handlers. Make sure to set root ViewGroup, where you want to get the click events as android:clickable="true"
or viewgroup.setClickable(true)
If you add views dynamically, make sure to call view.setClickable(false);
before adding it to the view hierarchy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With