android - 跟踪所有触摸事件
问题描述
情况
我想在我的应用程序中实现超时。如果用户在 2 分钟内没有触摸屏幕,则会显示一个不活动片段。
到目前为止
,我正在使用自定义Application
实现跟踪活动生命周期Application.ActivityLifecycleCallbacks
。这样我就知道哪个Activity
当前在顶部,并且可以访问它FragmentManager
以显示我Fragment
在超时时不活动。背景Thread
不断检查最后检测到的触摸是否超过 2 分钟。
问题
我不知道如何检测活动中发生的每一次触摸。我尝试添加一个OnTouchListener
to activity.getWindow().getDecorView().setOnTouchListener()
,但只有在触摸装饰视图时才会调用它。例如,如果触摸其顶部的按钮,则不会通知我的听众。activity.getContentScene()' returns null for me, so i can't access the root
ViewGroup` 也一样。
问题
我如何检测 Activity 或整个应用程序上发生的任何触摸?
解决方案
在您的活动中覆盖调度触摸事件
@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);
}
推荐阅读
- react-native - 使用 react-native-firebase 和 react-navigation 时出现错误“未定义不是对象(评估 'RNGestureHandlerModule.State')”
- c++ - 基本 std::regex,将查询转换为有效掩码
- kotlin - Kotlin 委托对象映射
- html - div 仅根据其他 div css 中的增加调整大小
- java - Spring Boot + Security:设置允许的来源时没有 Access-Control-Allow-Origin 标头
- in-app-purchase - Google In App Billing 中的 BillingFlowParams 无法使用真实 sku 开始计费
- reactjs - React Renders 在我的组件底部!没有顶部
- python-3.x - 当我将 DataFrame 保存为 CSV(python3)时,Pandas 更改编号
- command-line-interface - 交互模式没有以正确的方式接收选项
- php - 服务器上的安全 PHP 执行