Handling Touch Events
This method receives an instance of MotionEvent, a class that describes the touch event, including its
location and its action. The action describes the stage of the event:
Action constants Description
ACTION_DOWN user’s finger touches the screen
ACTION_MOVE user moves finger on the screen
ACTION_UP user lifts finger off the screen
ACTION_CANCEL a parent view has intercepted the touch event
In your implementation of onTouchEvent(MotionEvent), you can check the value of the action by
calling the MotionEvent method:
public final int getAction()
Let’s get to it. In BoxDrawingView.java, add a log tag and then an implementation of
onTouchEvent(MotionEvent) that logs a message for each of the four different actions.
Listing 31.5 Implementing BoxDrawingView (BoxDrawingView.java)
public class BoxDrawingView extends View {
private static final String TAG = "BoxDrawingView";
...
@Override
public boolean onTouchEvent(MotionEvent event) {
PointF current = new PointF(event.getX(), event.getY());
String action = "";
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
action = "ACTION_DOWN";
break;
case MotionEvent.ACTION_MOVE:
action = "ACTION_MOVE";
break;
case MotionEvent.ACTION_UP:
action = "ACTION_UP";
break;
case MotionEvent.ACTION_CANCEL:
action = "ACTION_CANCEL";
break;
}
Log.i(TAG, action + " at x=" + current.x +
", y=" + current.y);
return true;
}
}
Notice that you package your X and Y coordinates in a PointF object. You want to pass these two
values together as you go through the rest of the chapter. PointF is a container class provided by
Android that does this for you.
Run DragAndDraw and pull up Logcat. Touch the screen and drag your finger. You should see a report
of the X and Y coordinates of every touch action that BoxDrawingView receives.