我想要一个用于整个屏幕的 OnTouchListener。我尝试将所有 View 附加到 onTouchListener 但会生成错误的 touchEvents。我知道这可以通过重写方法来实现,我正在寻找的是监听器解决方案。谢谢!
这可以使用手势监听器来完成吗?
最佳答案
您可以插入一个 onSwipeListener 类,其中包含监听滑动操作的方法。然后,您可以为 Activity 的布局(LinearLayout/RelativeLayout)设置view.OnTouchListener,然后覆盖onSwipeListener的各种方法并插入各种任务。
下面是您可以创建的 onSwipeListener 类。
public class OnSwipeTouchListener implements OnTouchListener {
private final GestureDetector gestureDetector;
public OnSwipeTouchListener (Context ctx){
gestureDetector = new GestureDetector(ctx, new GestureListener());
}
@Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
private final class GestureListener extends SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
boolean result = false;
try {
float diffY = e2.getY() - e1.getY();
float diffX = e2.getX() - e1.getX();
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
onSwipeRight();
} else {
onSwipeLeft();
}
}
result = true;
}
else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
if (diffY > 0) {
onSwipeBottom();
} else {
onSwipeTop();
}
}
result = true;
} catch (Exception exception) {
exception.printStackTrace();
}
return result;
}
}
public void onSwipeRight() {
}
public void onSwipeLeft() {
}
public void onSwipeTop() {
}
public void onSwipeBottom() {
}
}
创建该类后,可以按如下方式调用它:
relativeLayout.setOnTouchListener(new OnSwipeTouchListener(context) {
public void onSwipeRight() {
//do something
}
public void onSwipeLeft() {
//do something
}
}
希望这有帮助!
关于java - 整个屏幕的OnTouchListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8453934/