Skip to content

Instantly share code, notes, and snippets.

Created January 18, 2021 17:19
Show Gist options
  • Save naman14/62162a7771a7352d5f61907ecb0ca50c to your computer and use it in GitHub Desktop.
Save naman14/62162a7771a7352d5f61907ecb0ca50c to your computer and use it in GitHub Desktop.
Handle possible child clicks in a parent viewgroup
package com.bharatpe.nativeloader
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
class ClickMonitoringView: LinearLayout {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle)
identify legitimate clicks on child views in a parent viewgroup
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
return false
private val mTapDetector: GestureDetector = GestureDetector(context, object: GestureDetector.SimpleOnGestureListener() {
override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
checkViewGroupClicks(e, this@ClickMonitoringView)
return true
private fun checkViewGroupClicks(ev: MotionEvent, viewGroup: ViewGroup): Boolean {
for (i in 0..viewGroup.childCount) {
val view = viewGroup.getChildAt(i);
if (view != null) {
// check if this view would have handled a click
if (verifyViewClick(ev, view)) {
return true
// if viewgroup, check all child views if they are going to handle a click
if (view is ViewGroup) {
return checkViewGroupClicks(ev, view)
return false
private fun verifyViewClick(ev: MotionEvent, view: View): Boolean {
val hitRect = Rect()
// find the view for which this click was performed and then check if that view
// had some clickListeners attached (which means they will handle some action)
if (hitRect.contains(ev.x.toInt(), ev.y.toInt()) && view.hasOnClickListeners()) {
// the child is going to do some action on this click, put some common logic here
Log.e("ClickMonitoringView", "child performed some action")
return true
return false
Copy link

At line 44 there shouldn't be a return. Having a return there does not allow checking other children of a ViewGroup except the first one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment