Handling Intercept touch event without extending ViewGroup
Solution 1
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
Solution 2
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.
Solution 3
Try add onTouchListener to RelativeLayout
RelativeLayout rl = (RelativeLayout) findViewById( R.id.relativeLauout );
rl.setOnTouchListener( new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// do something
return false;
}
});
or use method onTouchEvent from Activity
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
return super.onTouchEvent(event);
}
Solution 4
Try to return false in the onTouchEvent()
method of child views when processing ACTION_DOWN
event. So the forwarding touch events will not be sent to child views, aka event not consumed.
RuntimeException
Updated on June 08, 2022Comments
-
RuntimeException about 2 years
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 returningtrue
.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 inRelativeLayout
consumes event? I don't want to extendRelativeLayout
... -
RuntimeException over 10 yearsThanks for your answer... I have tried both of your ways before asking question... but it's not working :-(
-
kris14an over 10 yearsmayby try extend onTouchListener and set them to all views in layout