如果有人在Android应用中点击屏幕上的任何地方,如何触发事件?

gur*_*gui 24 events android

如果点击发生在应用程序屏幕的某个位置,我该如何捕获事件?是否有按钮或其他内容无关紧要.我只需要onClick()在整个应用程序屏幕上应用事件监听器.
这该怎么做?

Sam*_*iya 26

setonclicklistner 用于布局文件的主要布局....

像....的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>
Run Code Online (Sandbox Code Playgroud)

并为mainlayout设置click listener ...

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

    @Override
    public void onClick(View v) {

    }

 });
Run Code Online (Sandbox Code Playgroud)

  • OnClickListener的完整类名是什么?android.view.View.OnClickListener? (2认同)

Gen*_* S. 8

我相信最简单的方法是覆盖你的onUserInteractionActivity

请注意,当用户关注/关闭EditTexts和Spinners(可能还有其他小部件)时,它不会触发.但每次用户触摸屏幕或按下按钮时它都会触发.

但这使得无需在您的布局中构建侦听器或编写其他方法来处理这些侦听器,因此我相信这是获得所需内容的最无故障方法.


And*_*sik 8

你应该只覆盖Activity的dispatchTouchEvent(ev: MotionEvent)方法


看看 Kotlin 中的这个例子。这种方法不会影响您的应用程序中的任何 onClickListenters

/**
 * 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)
}
Run Code Online (Sandbox Code Playgroud)

或者查看完整的要点


Ale*_*rov 5

如果你想知道用户点击了屏幕上的任何地方,那么诀窍是覆盖 OnUserUnteraction():

"每当向活动分派按键、触摸或轨迹球事件时调用。如果您想知道用户在活动运行时以某种方式与设备进行了交互,请实现此方法。此回调和 {@link #onUserLeaveHint旨在帮助 Activity 智能地管理状态栏通知;具体来说,用于帮助 Activity 确定取消通知的适当时间......”

public abstract class BaseActivity extends Activity {
...
@Override
public void onUserInteraction() {
    Log.d(DEBUG_TAG,"Touch anywhere happened");
    super.onUserInteraction();
}
Run Code Online (Sandbox Code Playgroud)

在一些不活动后,我正在使用它来设置应用程序屏幕块。