此示例展示了如何将手势检测器添加到视图中。布局只是 Activity 中的一个 View。您可以使用相同的方法将手势检测器添加到任何类型的视图中。
我们将手势检测器添加到绿色的View。
MainActivity.java
基本思想是在视图中添加一个OnTouchListener。通常我们会在这里获取所有原始触摸数据(如ACTION_DOWN、ACTION_MOVE、ACTION_UP 等),但我们不会自己处理,而是将其转发给手势检测器来解释触摸数据。
我们使用的是SimpleOnGestureListener。这个手势检测器的好处是我们只需要覆盖我们需要的手势。在这里的例子中,我包括了很多。您可以删除不需要的那些。 (不过,您应该始终在 onDown() 中返回 true。返回 true 表示我们正在处理该事件。返回 false 将使系统停止为我们提供更多触摸事件。)
public class MainActivity extends AppCompatActivity {
private GestureDetector mDetector;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// this is the view we will add the gesture detector to
View myView = findViewById(R.id.my_view);
// get the gesture detector
mDetector = new GestureDetector(this, new MyGestureListener());
// Add a touch listener to the view
// The touch listener passes all its events on to the gesture detector
myView.setOnTouchListener(touchListener);
}
// This touch listener passes everything on to the gesture detector.
// That saves us the trouble of interpreting the raw touch events
// ourselves.
View.OnTouchListener touchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// pass the events to the gesture detector
// a return value of true means the detector is handling it
// a return value of false means the detector didn't
// recognize the event
return mDetector.onTouchEvent(event);
}
};
// In the SimpleOnGestureListener subclass you should override
// onDown and any other gesture that you want to detect.
class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onDown(MotionEvent event) {
Log.d("TAG","onDown: ");
// don't return false here or else none of the other
// gestures will work
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
Log.i("TAG", "onSingleTapConfirmed: ");
return true;
}
@Override
public void onLongPress(MotionEvent e) {
Log.i("TAG", "onLongPress: ");
}
@Override
public boolean onDoubleTap(MotionEvent e) {
Log.i("TAG", "onDoubleTap: ");
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
Log.i("TAG", "onScroll: ");
return true;
}
@Override
public boolean onFling(MotionEvent event1, MotionEvent event2,
float velocityX, float velocityY) {
Log.d("TAG", "onFling: ");
return true;
}
}
}
运行此项目是一种快速设置,因此我建议您尝试一下。注意日志事件发生的方式和时间。