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

setonclicklistner for main layout of your layout file....

Like....main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/mainlayout">
 <!- Your other view->
</Relativelayout>

and set click listener for mainlayout...

 RelativeLayout rlayout = (RelativeLayout) findViewById(R.id.mainlayout);
 rlayout.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

    }

 });

I believe the easiest way is to override onUserInteraction in your Activity

Just be aware that it won't fire when users focus on/off EditTexts and Spinners (probably other Widgets too). But it will fire every time the user touches the screen or presses a Button.

But this makes it unnecessary to build listeners into your layouts or write additional methods to handle those listeners, so I believe it's the most trouble-free way to get what you want.


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

Tags:

Events

Android