How to Pass a View's Onclick Event to Its Parent on Android

How to pass a view's onClick event to its parent on Android?

I think you need to use one of those methods in order to be able to intercept the event before it gets sent to the appropriate components:

Activity.dispatchTouchEvent(MotionEvent) - This allows your Activity to intercept all touch events before they are dispatched to the window.

ViewGroup.onInterceptTouchEvent(MotionEvent) - This allows a ViewGroup to watch events as they are dispatched to child Views.

ViewParent.requestDisallowInterceptTouchEvent(boolean) - Call this upon a parent View to indicate that it should not intercept touch events with onInterceptTouchEvent(MotionEvent).

More information here.

Hope that helps.

Android: Let Parent View Handle On Click

Ensuring you got no OnClickListener assigned to any of the childs of your RelativeLayout shall usually suffice for them to not receive clicks. Also check if you got no android:cliclable="true" set by any chance for it. Then once you assing OnClickListener to your RelativeLayout it should get all the clicks.

Passing touch events to the parent view

Thank you everyone for answering the question. But I was able to figure it out in a much simpler manner. Since my ViewSwitcher wasn't detecting the touch event, I intercepted the touch event, called the onTouchEvent() and returned false. Here:

@Override
public boolean onInterceptTouchEvent(MotionEvent ev)
{
onTouchEvent(ev);
return false;
}

By overriding the onInterceptTouchEvent(), I was able to intercept the touch event in the activity. Then I called the onTouchEvent() in the ViewSwitcher which handles the switching of the ListViews. And finally by returning false, it makes sure that the ViewGroup doesn't consume the event.

How to pass onClick event from parent to children?

set your click for child View and when needed add also OnClickListener for parent, and inside call cardHeader.performClick() or cardHeader.callOnClick() method

cardHeader.setOnClickListener((View v) -> {
// do something
});

if (isTablet(getContext())) {
cardView.setOnClickListener((View v) -> {
cardHeader.callOnClick();
});
}


Related Topics



Leave a reply



Submit