Android: Detect if user touches and drags out of button region?

Viewed 46894

In Android, how can we detect if a user touches on button and drags out of region of this button?

10 Answers

Reuseable Kotlin Solution

I started with two custom extension functions:

val MotionEvent.up get() = action == MotionEvent.ACTION_UP

fun MotionEvent.isIn(view: View): Boolean {
    val rect = Rect(view.left, view.top, view.right, view.bottom)
    return rect.contains((view.left + x).toInt(), (view.top + y).toInt())
}

Then listen to touches on the view. This will only fire if ACTION_DOWN was originally on the view. When you release your finger, it will check if it was still on the view.

myView.setOnTouchListener { view, motionEvent ->
    if (motionEvent.up && !motionEvent.isIn(view)) {
        // Talk your action here
    }
    false
}

If drag to outside of view, 'ACTION_CANCEL' event call. So need disallow parent view to intercept touch event:

override fun dispatchTouchEvent(event: MotionEvent): Boolean {
    when (event.action) {
        MotionEvent.ACTION_DOWN -> {
            (parent as? ViewGroup?)?.requestDisallowInterceptTouchEvent(true)
        }
        MotionEvent.ACTION_UP -> {
            (parent as? ViewGroup?)?.requestDisallowInterceptTouchEvent(false)
        }
        else -> {
        }
    }
    return true
}

and then you can check touch point is outside of your view or not!

Related