首页 > 解决方案 > 跟踪所有触摸事件

问题描述

情况
我想在我的应用程序中实现超时。如果用户在 2 分钟内没有触摸屏幕,则会显示一个不活动片段。

到目前为止
,我正在使用自定义Application实现跟踪活动生命周期Application.ActivityLifecycleCallbacks。这样我就知道哪个Activity当前在顶部,并且可以访问它FragmentManager以显示我Fragment在超时时不活动。背景Thread不断检查最后检测到的触摸是否超过 2 分钟。

问题
我不知道如何检测活动中发生的每一次触摸。我尝试添加一个OnTouchListenerto activity.getWindow().getDecorView().setOnTouchListener(),但只有在触摸装饰视图时才会调用它。例如,如果触摸其顶​​部的按钮,则不会通知我的听众。activity.getContentScene()' returns null for me, so i can't access the rootViewGroup` 也一样。

问题
我如何检测 Activity 或整个应用程序上发生的任何触摸?

标签: androidandroid-activitytouch-eventrootview

解决方案


在您的活动中覆盖调度触摸事件

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    Rect viewRect = new Rect();
    view.getGlobalVisibleRect(viewRect);

//or 

  int x= ev.getRawX();
     int y= ev.getRawY();


         if(/*check bounds of your view*/){
          // set your views visiblity to gone or what you want. 
         }
      //for prevent consuming the event.


    return super.dispatchTouchEvent(ev);
}

推荐阅读