Android - basic gesture detection using MotionEventCompat class
A touch gesture occurs when a user places one or more fingers on the touch screen.
In order to get a touch gesture of a touch event we can use GestureDetectorCompat or MotionEventCompat clases. These classes are in the Support library.
In this blog, we will discuss about detecting touch gestures using MotionEventCompat class.
Detect touch events on an Activity or View
To detect touch gestures on an Activity or View, override the onTouchEvent( ) method.
The following code override the onTouchEvent() method in an Activity, but you can also override this method when subclassing a View.
The following code uses getActionMasked() to get the action user performed from event parameter.
public class MainActivity extends Activity {
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_CANCEL) :
Log.d(DEBUG_TAG,"Action was CANCEL");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
Detect touch events on a single view
Also, you can detect touch gesture on any particular view. You can do this by attaching OnTouchlistener using setOnTouchlistener() method.
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// ... Respond to touch events
return true;
}
});
0 Comment(s)