我是 android 的初学者,我正在学习 newboston 教程。我发现了这段用于手势识别的代码。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myMessage = (TextView) findViewById(R.id.myMessage);
this.gestureDetector = new GestureDetectorCompat(this, this);
gestureDetector.setOnDoubleTapListener(this);
}
我查阅了 GestureDetectorCompat
的文档,可以看到使用的构造函数是 GestureDetectorCompat(Context context, GestureDetector.OnGestureListener listener)
但是,我无法理解 new GestureDetectorCompat(this, this);
将如何创建此对象。 (this, this)
指的是什么?它从哪里来?是否有另一种创建此对象的方法可以帮助我理解这一点?
最佳答案
第一个参数this
是您当前 Activity 的上下文。 (所以关于上下文的想法的问题 What is 'Context' on Android? )第二个又是 this
,因为你的 Activity 应该实现 implements OnGestureListener, OnDoubleTapListener
这就是为什么你可以写而不是
... new GestureDetector(this, new OnGestureListener() {...} );
//and then
gestureDetector.setOnDoubleTapListener(new OnDoubleTapListener() {...});
只是
... new GestureDetectorCompat(this, this);
//and
gestureDetector.setOnDoubleTapListener(this);
如果您不想使用您发布的构造(使用 this
参数),那么您可以轻松地使用像这样的完整构造(只是完整使用的一个例子):
gestureDetector.setOnDoubleTapListener(new OnDoubleTapListener() {
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return false;
}
@Override
public boolean onDoubleTap(MotionEvent e) {
mapView.getController().zoomInFixing((int) e.getX(), (int) e.getY());
return false;
}
//you could override more methods here if you want
}
关于java - Android Gestures 代码解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34317005/