Android:同一 View 上的多个手势检测器

标签 android gesture

我有一个用 ScrollView 包装的 TextView。我需要做的是在我的 TextView 上检测比例和常用手势(如点击、双击和其他)。另外,我想要一些手势来处理标准处理程序(例如滚动)。 我只是无法掌握基础知识,我不知道为此编写什么代码。我为它们制作了两个检测器(ScaleGestureDetector 和 GestureDetector)和监听器。另外,我像这样为我的 TextView 设置了 onTouchListener:

tw.setOnTouchListener(new OnTouchListener() {
    public boolean onTouch(View view, MotionEvent motionEvent) {
        if (!gestureDetector.onTouchEvent(motionEvent)) {
            scaleGestureDetector.onTouchEvent(motionEvent);
        };
        return true;
    }
});

没有检测到手势。我用谷歌搜索的每个示例都使用一个检测器。有人可以帮我解决这个概念吗?如何在同一 View 上检测缩放(或捏合缩放)、双击、单击等?

最佳答案

一种解决方案是为您的两个检测器调用 onTouchEvent:

tw.setOnTouchListener(new OnTouchListener() {
    public boolean onTouch(View view, MotionEvent motionEvent) {
        gestureDetector.onTouchEvent(motionEvent);
        scaleGestureDetector.onTouchEvent(motionEvent);
        return true;
    }
});

然而,这可能会导致不良行为,因为两个探测器可能会同时触发;例如,一个手势可能被识别为缩放手势和滚动手势。

为了解决这个问题,您可以引入一个新变量 scaleOngoing 来跟踪缩放事件是否正在进行:

scaleGestureDetector = new ScaleGestureDetector(context, new ScaleGestureDetector.OnScaleGestureListener() {
    public void onScaleEnd(ScaleGestureDetector detector) {
        scaleOngoing = false;
    }
    public boolean onScaleBegin(ScaleGestureDetector detector) {
        scaleOngoing = true;
        return true;
    }
    public boolean onScale(ScaleGestureDetector detector) {
        // do scaling here
        return false;
    }
});

然后让您的 GestureDetector 的监听器检查是否正在发生缩放手势:

mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        if(!scaleOngoing) {
            // do scrolling here
         }
         return true;
    }
});  

关于Android:同一 View 上的多个手势检测器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26345832/

相关文章:

ios - 在具有不同 zPosition 的 UIView 中管理手势

android - FirebaseInstanceId : Google Play services missing or without correct permission

java - 无法更改 Android 中的自定义操作栏背景颜色

android - 用 Greenrobot Eventbus 替换广播接收器是否可以触发基于事件的功能和从服务到 Activity 的数据传输?

android - 如何检测android中的L形手势?

iphone - 有没有用于iPhone开发的高级手势库?

android - 生成位图的时间戳 - Android

java - Robolectric - AndroidStudio - 找不到参数的方法 testCompile()

WebView Activity 中的 Android 左/右滑动手势(点击链接和垂直滚动)

ios - 使用 hitTest() 或 point(inside, with event) 从添加到 keyWindow 的 View 转发事件