android - Swift 检测器手势 android

标签 android gesture

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (gestureDetector.onTouchEvent(event)) {
        return true;
    }
    return super.onTouchEvent(event);
}
private void onLeftSwipe() {
// Do something
    System.out.println("left swipe");
}

private void onRightSwipe() {
// Do something
    System.out.println("right swipe");
}

// Private class for gestures
private class SwipeGestureDetector extends SimpleOnGestureListener {
    // Swipe properties, you can change it to make the swipe
    // longer or shorter and speed
    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 200;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        try {
            float diffAbs = Math.abs(e1.getY() - e2.getY());
            float diff = e1.getX() - e2.getX();

            if (diffAbs > SWIPE_MAX_OFF_PATH)
            return false;

            // Left swipe
            if (diff > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                SlidingMenuActivity.this.onLeftSwipe();

                // Right swipe
            } else if (-diff > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                SlidingMenuActivity.this.onRightSwipe();
            }
        } catch (Exception e) {
            Log.e("YourActivity", "Error on gestures");
        }
        return false;
    }
}

我有,但它不起作用,我无法检测到向左或向右滑动。我已经在我的类之上和 Activity 的 onCreate 方法中声明了 private GestureDetector gestureDetector;

gestureDetector = new GestureDetector(new SwipeGestureDetector());

但是它不起作用,没有打印任何东西?我正在使用 kitkat nexus 4。

最佳答案

您必须将监听器应用到您喜欢的 View 上,例如:

myView.setOnTouchListener(new SwipeGestureDetector(this)....

关于android - Swift 检测器手势 android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23158750/

相关文章:

android - 如何在 Android 中将值从一个 Activity 传递到另一个 Activity?

android - AsyncTask 在 Android 4.0 及更高版本中不执行

android - 未检测到滑动

SwiftUI - DragGesture 和 .onDelete 冲突

android - 如何为不同版本的 Android 设置不同的小部件?

java - 如何实现GestureListener.onFling()方法

ios - IOS 中的手势模式识别器。

java - 数据对齐与缓存局部性

android - Android 中的 ApplicationInfo 适配器仅显示具有启动器 Intent 的应用程序

java - 升级 Firebase 后 Android Unresolved 依赖关系