how to fire an event when someone clicks anywhere on the screen in an android app?

前端 未结 7 555
暗喜
暗喜 2020-12-29 03:06

how can I catch the event when click occurs somewhere on the app screen? It doesn\'t matter if there is a button or something else. I just need to apply an onClick()

7条回答
  •  悲&欢浪女
    2020-12-29 03:58

    You should just override Activity's dispatchTouchEvent(ev: MotionEvent) method


    Look at this example in Kotlin. This approach will not affect any onClickListenters in your app

    /**
     * On each touch event:
     * Check is [snackbar] present and displayed
     * and dismiss it if user touched anywhere outside it's bounds
     */
    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        // dismiss shown snackbar if user tapped anywhere outside snackbar
        snackbar?.takeIf { it.isShown }?.run {
            val touchPoint = Point(Math.round(ev.rawX), Math.round(ev.rawY))
            if (!isPointInsideViewBounds(view, touchPoint)) {
                dismiss()
                snackbar = null // set snackbar to null to prevent this block being executed twice
            }
        }
    
        // call super
        return super.dispatchTouchEvent(ev)
    }
    

    Or check out the full gist

提交回复
热议问题