我想有一个OnTouchListener为整个屏幕。我试过将所有视图附加到onTouchListener,但产生坏的touchEvents。我知道这可以通过重写方法来实现,我正在寻找的是一个侦听器解决方案。谢谢!
可以使用手势侦听器吗?
你可以插入一个onSwipeListener类,其中包含侦听滑动动作的方法。然后你可以设置视图。OnTouchListener用于活动的布局(LinearLayout/RelativeLayout),然后覆盖onSwipeListener的各种方法并插入各种任务。
下面是你可以创建的onswipellistener类。
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
}
}
希望这对你有帮助!