Created
January 18, 2021 17:19
-
-
Save naman14/62162a7771a7352d5f61907ecb0ca50c to your computer and use it in GitHub Desktop.
Handle possible child clicks in a parent viewgroup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.bharatpe.nativeloader | |
import android.content.Context | |
import android.graphics.Rect | |
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 { | |
mTapDetector.onTouchEvent(ev) | |
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() | |
view.getHitRect(hitRect) | |
// 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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
At line 44 there shouldn't be a
return
. Having areturn
there does not allow checking other children of aViewGroup
except the first one.