setOnDragListener 如何监听左划右划
时间: 2024-01-12 21:02:28 浏览: 69
ViewPager判断是向左划还是右划的实例
setOnDragListener 通常用于监听 View 的拖动事件,而左划右划属于手势事件,可以通过 GestureDetector 来监听。下面是一个示例代码:
```java
public class MyView extends View {
private GestureDetector mGestureDetector;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
mGestureDetector = new GestureDetector(context, new MyGestureListener());
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return mGestureDetector.onTouchEvent(event);
}
private class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
@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;
}
}
} catch (Exception exception) {
exception.printStackTrace();
}
return result;
}
}
public void onSwipeRight() {
// 处理右划事件
}
public void onSwipeLeft() {
// 处理左划事件
}
}
```
在这个示例代码中,MyView 继承自 View,重写 onTouchEvent 方法,在该方法中将触摸事件交给 GestureDetector 处理。在 GestureDetector 的回调函数中,判断手势是否为左右滑动,如果是,则调用 MyView 中的 onSwipeLeft 或 onSwipeRight 方法进行处理。
阅读全文