我正在编写简单的代码来检测所有手势,如滑动、滚动等,并打算实现接口(interface) GestureDetector.OnGestureListener
用于覆盖它的方法,但我知道同样可以用 GestureDetector.SimpleOnGestureListener
完成.据我所知SimpleOnGestureListener
是一个实现了 OnGestureListener
的类, OnDoubleTapListener
和 OnContextClickListener
接口(interface),如果我错了,请纠正我。
在 Android Developer 网站页面上写着 -
If you only want to process a few gestures, you can extend
GestureDetector.SimpleOnGestureListener
instead of implementing theGestureDetector.OnGestureListener
interface.
GestureDetector.SimpleOnGestureListener
provides an implementation for all of theon<TouchEvent>
methods by returning false for all of them. Thus you can override only the methods you care about. For example, the snippet below creates a class that extendsGestureDetector.SimpleOnGestureListener
and overridesonFling()
andonDown()
.
我在这里有几个问题,
1) 为什么要使用GestureDetector.SimpleOnGestureListener
如果我们可以实现 GestureDetector.OnGestureListener
以及其他使用这些方法的接口(interface)?
2) 是GestureDetector.SimpleOnGestureListener
一样没有区别?是为了简化编码?
最佳答案
来自 GestureDetector.SimpleOnGestureListener 的文档
A convenience class to extend when you only want to listen for a subset of all the gestures. This implements all methods in the GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener, and GestureDetector.OnContextClickListener but does nothing and return false for all applicable methods.
如果您只想实现一些方法(不是全部),SimpleOnGestureListener
具有不执行任何操作的默认实现。这可以防止您的代码被多种无所事事的方法弄得乱七八糟。从功能的角度来看,使用 SimpleOnGestureListener
还是直接实现接口(interface)都没有关系。
源代码
public static class SimpleOnGestureListener implements OnGestureListener, OnDoubleTapListener,
OnContextClickListener {
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
public void onLongPress(MotionEvent e) {
}
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
return false;
}
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return false;
}
public void onShowPress(MotionEvent e) {
}
public boolean onDown(MotionEvent e) {
return false;
}
public boolean onDoubleTap(MotionEvent e) {
return false;
}
public boolean onDoubleTapEvent(MotionEvent e) {
return false;
}
public boolean onSingleTapConfirmed(MotionEvent e) {
return false;
}
public boolean onContextClick(MotionEvent e) {
return false;
}
}
关于java - Android 开发 - GestureDetector.OnGestureListener 或 GestureDetector.SimpleOnGestureListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37709883/