手势识别官方教程(2)识别常见手势用GestureDetector+手势回调接口/手势抽象类
简介
GestureDetector识别手势。
GestureDetector.OnGestureListener是识别手势后的回调接口。
GestureDetector.SimpleOnGestureListener是抽象类。
基本步骤:
- 构造GestureDetector,注意要传入context和listener(GestureDetector.OnGestureListener或GestureDetector.SimpleOnGestureListener)
- 在Activity/View的onTouchEvent或onTouchEventListener回调中,调用mDetector.onTouchEvent(event);
- 处理手势成功识别后的回调,如onFling()
Detecting Common Gestures
A "touch gesture" occurs when a user places one or more fingers on the touch screen, and your application interprets that pattern of touches as a particular gesture. There are correspondingly two phases to gesture detection:
手势识别分两步:
- 截取到touch事件
- 分析它是否是支持的手势
- Gathering data about touch events.
- Interpreting the data to see if it meets the criteria for any of the gestures your app supports.
Support Library Classes
The examples in this lesson use the GestureDetectorCompat
and MotionEventCompat
classes. These classes are in the Support Library. You should use Support Library classes where possible to provide compatibility with devices running Android 1.6 and higher. Note that MotionEventCompat
is not a replacement for the MotionEvent
class. Rather, it provides static utility methods to which you pass your MotionEvent
object in order to receive the desired action associated with that event.
注意 GestureDetectorCompat 和 MotionEventCompat是扩展库里的,并且MotionEventCompat 也不是用来替换 MotionEvent 的。
1.Gather Data 截取touch事件的两种方法
When a user places one or more fingers on the screen, this triggers the callback onTouchEvent()
on the View that received the touch events. For each sequence of touch events (position, pressure, size, addition of another finger, etc.) that is ultimately identified as a gesture, onTouchEvent()
is fired several times.
The gesture starts when the user first touches the screen, continues as the system tracks the position of the user's finger(s), and ends by capturing the final event of the user's fingers leaving the screen. Throughout this interaction, the MotionEvent
delivered to onTouchEvent()
provides the details of every interaction. Your app can use the data provided by the MotionEvent
to determine if a gesture it cares about happened.
识别手势都是从触摸事件开始,有两种处理触摸事件的方法:
1,直接处理法:在activity和view(含自定义)重写onTouchEvent()方法
2,回调法:给已经封装好的view设置一个View.OnTouchListener重写onTouch()方法
1.1 Capturing touch events for an Activity or View
To intercept touch events in an Activity or View, override the onTouchEvent()
callback.
The following snippet uses getActionMasked()
to extract the action the user performed from the event
parameter. This gives you the raw data you need to determine if a gesture you care about occurred:
1 public class MainActivity extends Activity { 2 ... 3 // This example shows an Activity, but you would use the same approach if 4 // you were subclassing a View. 5 @Override 6 public boolean onTouchEvent(MotionEvent event){ 7 8 int action = MotionEventCompat.getActionMasked(event); 9 10 switch(action) { 11 case (MotionEvent.ACTION_DOWN) : 12 Log.d(DEBUG_TAG,"Action was DOWN"); 13 return true; 14 case (MotionEvent.ACTION_MOVE) : 15 Log.d(DEBUG_TAG,"Action was MOVE"); 16 return true; 17 case (MotionEvent.ACTION_UP) : 18 Log.d(DEBUG_TAG,"Action was UP"); 19 return true; 20 case (MotionEvent.ACTION_CANCEL) : 21 Log.d(DEBUG_TAG,"Action was CANCEL"); 22 return true; 23 case (MotionEvent.ACTION_OUTSIDE) : 24 Log.d(DEBUG_TAG,"Movement occurred outside bounds " + 25 "of current screen element"); 26 return true; 27 default : 28 return super.onTouchEvent(event); 29 } 30 }
You can then do your own processing on these events to determine if a gesture occurred. This is the kind of processing you would have to do for a custom gesture. However, if your app uses common gestures such as double tap, long press, fling, and so on, you can take advantage of the GestureDetector
class.GestureDetector
makes it easy for you to detect common gestures without processing the individual touch events yourself. This is discussed below in Detect Gestures.
1.2 Capturing touch events for a single view
As an alternative to onTouchEvent()
, you can attach an View.OnTouchListener
object to any View
object using the setOnTouchListener()
method. This makes it possible to to listen for touch events without subclassing an existing View
. For example:
1 View myView = findViewById(R.id.my_view); 2 myView.setOnTouchListener(new OnTouchListener() { 3 public boolean onTouch(View v, MotionEvent event) { 4 // ... Respond to touch events 5 return true; 6 } 7 });
Beware of creating a listener that returns false
for the ACTION_DOWN
event. If you do this, the listener will not be called for the subsequent ACTION_MOVE
and ACTION_UP
string of events. This is because ACTION_DOWN
is the starting point for all touch events.
If you are creating a custom View, you can override onTouchEvent()
, as described above.
2.Detect Gestures开始分析识别手势
Android provides the GestureDetector
class for detecting common gestures. Some of the gestures it supports include onDown()
, onLongPress()
, onFling()
, and so on. You can use GestureDetector
in conjunction with the onTouchEvent()
method described above.
GestureDetector 封装了常用的手势并心回调的方式通知已经识别的手势,如Down,LongPress,FLing,Scroll等。见: GestureDetector.OnGestureListener
注意要在 onTouchEvent()中调用 GestureDetector.onTouchEvent(xxx); 才能识别手势。
2.1 Detecting All Supported Gestures
When you instantiate a GestureDetectorCompat
object, one of the parameters it takes is a class that implements the GestureDetector.OnGestureListener
interface.GestureDetector.OnGestureListener
notifies users when a particular touch event has occurred. To make it possible for your GestureDetector
object to receive events, you override the View or Activity's onTouchEvent()
method, and pass along all observed events to the detector instance.
In the following snippet, a return value of true
from the individual on<TouchEvent>
methods indicates that you have handled the touch event. A return value of false
passes events down through the view stack until the touch has been successfully handled.
注意 TouchEvent()的返回值,返回true表示在本函数中处理了,false表示本函数没有处理,那么事件继续传
Run the following snippet to get a feel for how actions are triggered when you interact with the touch screen, and what the contents of the MotionEvent
are for each touch event. You will realize how much data is being generated for even simple interactions.
1 public class MainActivity extends Activity implements 2 GestureDetector.OnGestureListener, 3 GestureDetector.OnDoubleTapListener{ 4 5 private static final String DEBUG_TAG = "Gestures"; 6 private GestureDetectorCompat mDetector; 7 8 // Called when the activity is first created. 9 @Override 10 public void onCreate(Bundle savedInstanceState) { 11 super.onCreate(savedInstanceState); 12 setContentView(R.layout.activity_main); 13 // Instantiate the gesture detector with the 14 // application context and an implementation of 15 // GestureDetector.OnGestureListener 16 mDetector = new GestureDetectorCompat(this,this); 17 // Set the gesture detector as the double tap 18 // listener. 19 mDetector.setOnDoubleTapListener(this); 20 } 21 22 @Override 23 public boolean onTouchEvent(MotionEvent event){ 24 this.mDetector.onTouchEvent(event); 25 // Be sure to call the superclass implementation 26 return super.onTouchEvent(event); 27 } 28 29 @Override 30 public boolean onDown(MotionEvent event) { 31 Log.d(DEBUG_TAG,"onDown: " + event.toString()); 32 return true; 33 } 34 35 @Override 36 public boolean onFling(MotionEvent event1, MotionEvent event2, 37 float velocityX, float velocityY) { 38 Log.d(DEBUG_TAG, "onFling: " + event1.toString()+event2.toString()); 39 return true; 40 } 41 42 @Override 43 public void onLongPress(MotionEvent event) { 44 Log.d(DEBUG_TAG, "onLongPress: " + event.toString()); 45 } 46 47 @Override 48 public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, 49 float distanceY) { 50 Log.d(DEBUG_TAG, "onScroll: " + e1.toString()+e2.toString()); 51 return true; 52 } 53 54 @Override 55 public void onShowPress(MotionEvent event) { 56 Log.d(DEBUG_TAG, "onShowPress: " + event.toString()); 57 } 58 59 @Override 60 public boolean onSingleTapUp(MotionEvent event) { 61 Log.d(DEBUG_TAG, "onSingleTapUp: " + event.toString()); 62 return true; 63 } 64 65 @Override 66 public boolean onDoubleTap(MotionEvent event) { 67 Log.d(DEBUG_TAG, "onDoubleTap: " + event.toString()); 68 return true; 69 } 70 71 @Override 72 public boolean onDoubleTapEvent(MotionEvent event) { 73 Log.d(DEBUG_TAG, "onDoubleTapEvent: " + event.toString()); 74 return true; 75 } 76 77 @Override 78 public boolean onSingleTapConfirmed(MotionEvent event) { 79 Log.d(DEBUG_TAG, "onSingleTapConfirmed: " + event.toString()); 80 return true; 81 } 82 }
2.2 Detecting a Subset of Supported Gestures
If you only want to process a few gestures, you can extend GestureDetector.SimpleOnGestureListener
instead of implementing the GestureDetector.OnGestureListener
interface.
GestureDetector.SimpleOnGestureListener
provides an implementation for all of the on<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 extends GestureDetector.SimpleOnGestureListener
and overrides onFling()
and onDown()
.
GestureDetector.SimpleOnGestureListener 是个使用起来比GestureDetector.OnGestureListener简单手势回调的接口,可只实现感举的手势。
Whether or not you use GestureDetector.OnGestureListener
, it's best practice to implement an onDown()
method that returns true
. This is because all gestures begin with an onDown()
message. If you return false
from onDown()
, as GestureDetector.SimpleOnGestureListener
does by default, the system assumes that you want to ignore the rest of the gesture, and the other methods of GestureDetector.OnGestureListener
never get called. This has the potential to cause unexpected problems in your app. The only time you should return false
from onDown()
is if you truly want to ignore an entire gesture.
1 public class MainActivity extends Activity { 2 3 private GestureDetectorCompat mDetector; 4 5 @Override 6 public void onCreate(Bundle savedInstanceState) { 7 super.onCreate(savedInstanceState); 8 setContentView(R.layout.activity_main); 9 mDetector = new GestureDetectorCompat(this, new MyGestureListener()); 10 } 11 12 @Override 13 public boolean onTouchEvent(MotionEvent event){ 14 this.mDetector.onTouchEvent(event); 15 return super.onTouchEvent(event); 16 } 17 18 class MyGestureListener extends GestureDetector.SimpleOnGestureListener { 19 private static final String DEBUG_TAG = "Gestures"; 20 21 @Override 22 public boolean onDown(MotionEvent event) { 23 Log.d(DEBUG_TAG,"onDown: " + event.toString()); 24 return true; 25 } 26 27 @Override 28 public boolean onFling(MotionEvent event1, MotionEvent event2, 29 float velocityX, float velocityY) { 30 Log.d(DEBUG_TAG, "onFling: " + event1.toString()+event2.toString()); 31 return true; 32 } 33 } 34 }