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

(gtxtreme123) #1

Chapter 31  Custom Views and Touch Events


And that is it. You have now created a view that captures its own touch events and performs its own
drawing.


Challenge: Saving State


Figure out how to persist your boxes across orientation changes from within your View. This can be
done with the following View methods:


protected Parcelable onSaveInstanceState()
protected void onRestoreInstanceState(Parcelable state)


These methods do not work like Activity and Fragment’s onSaveInstanceState(Bundle). First,
they will only be called if your View has an ID. Second, instead of taking in a Bundle, they return and
process an object that implements the Parcelable interface. We recommend using a Bundle as the
Parcelable instead of implementing a Parcelable class yourself. (Implementing the Parcelable
interface is complicated. It is better to avoid doing so when possible.)


Finally, you must also maintain the saved state of BoxDrawingView’s parent, the View class. Save the
result of super.onSaveInstanceState() in your new Bundle and send that same result to the super
class when calling super.onRestoreInstanceState(Parcelable).


Challenge: Rotating Boxes


For a harder challenge, make it so that you can use a second finger to rotate your rectangles. To do this,
you will need to handle multiple pointers in your MotionEvent handling code. You will also need to
rotate your canvas.


When dealing with multiple touches, you need these extra ideas:


pointer index tells you which pointer in the current set of pointers the event is for

pointer ID gives you a unique ID for a specific finger in a gesture

The pointer index may change, but the pointer ID will not.


For more details, check out the documentation for the following MotionEvent methods:


public final int getActionMasked()
public final int getActionIndex()
public final int getPointerId(int pointerIndex)
public final float getX(int pointerIndex)
public final float getY(int pointerIndex)


Also look at the documentation for the ACTION_POINTER_UP and ACTION_POINTER_DOWN constants.

Free download pdf