Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1
Tracking across motion events

Back in BoxDrawingView, use your new Box object to track your drawing state.


Listing 31.7  Adding drag lifecycle methods (BoxDrawingView.java)


public class BoxDrawingView extends View {
private static final String TAG = "BoxDrawingView";


private Box mCurrentBox;
private List mBoxen = new ArrayList<>();
...
@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";
// Reset drawing state
mCurrentBox = new Box(current);
mBoxen.add(mCurrentBox);
break;
case MotionEvent.ACTION_MOVE:
action = "ACTION_MOVE";
if (mCurrentBox != null) {
mCurrentBox.setCurrent(current);
invalidate();
}
break;
case MotionEvent.ACTION_UP:
action = "ACTION_UP";
mCurrentBox = null;
break;
case MotionEvent.ACTION_CANCEL:
action = "ACTION_CANCEL";
mCurrentBox = null;
break;
}


Log.i(TAG, action + " at x=" + current.x +
", y=" + current.y);


return true;
}
}


Any time an ACTION_DOWN motion event is received, you set mCurrentBox to be a new Box with its
origin as the event’s location. This new Box is added to the list of boxes. (In the next section, when you
implement custom drawing, BoxDrawingView will draw every Box within this list to the screen.)


As the user’s finger moves around the screen, you update mCurrentBox.mCurrent. Then, when the
touch is canceled or when the user’s finger leaves the screen, you null out mCurrentBox to end your
draw motion. The Box is complete; it is stored safely in the list but will no longer be updated about
motion events.


Notice the call to invalidate() in the case of ACTION_MOVE. This forces BoxDrawingView to redraw
itself so that the user can see the box while dragging across the screen. Which brings you to the next
step: drawing the boxes to the screen.

Free download pdf