Ch.27 Touch Screens
Understanding MotionEvents
The MotionEvent Object
Receiving MotionEvent Objects
- When we want touch events to do something new with a particular View object, we can extend the class, override the
onTouchEvent()
method, and put our logic there. We can also implement theView.OnTouchListener
interface and set up a callback handler on theView
object. By setting up a callback handler withonTouch()
,MotionEvents
will be delivered there first before they go to the View’sonTouchEvent()
method. Only if theonTouch()
method returned false would our View’sonTouchEvent()
method get called.
Understanding MotionEvent Contents
Recycling MotionEvents
MotionEvent.obtaion
,MotionEvent.recyle
Using VelocityTracker
- To use
VelocityTracker
, you first get an instance of aVelocityTracker
by calling the static methodVelocityTracker.obtain()
. You can then addMotionEvent
objects to it with theaddMovement(MotionEvent ev)
method. You would call this method in your handler that receivesMotionEvent
objects, from a handler method such asonTouch()
, or from a view’sonTouchEvent()
. TheVelocityTracker
uses theMotionEvent
objects to figure out what is going on with the user’s touch sequence. OnceVelocityTracker
has at least twoMotionEvent
objects in it, we can use the other methods to find out what’s happening. - When you are finished with the
VelocityTracker
object you got with theobtain()
method, call theVelocityTracker
object’srecycle()
method.
Multitouch
The Basics of Multitouch
- At a basic level, the methods of
MotionEvent
are the same; that is, we callgetAction()
,getDownTime()
,getX()
, and so on. However, when more than one finger is touching the screen, theMotionEvent
object must include information from all fingers, with some caveats. The action value fromgetAction()
is for one finger, not all. The down time value is for the very first finger down and measures the time as long as at least one finger is down. The location valuesgetX()
andgetY()
, as well asgetPressure()
andgetSize()
, can take an argument for the finger; therefore, you need to use a pointer index value to request the information for the finger you’re interested in. There are method calls that we used previously that did not take any argument to specify a finger (for example,getX()
,getY()
), so which finger would the values be for if we used those methods? You can figure it out, but it takes some work. Therefore, if you don’t take into account multiple fingers all of the time, you might end up with some strange results.
Understanding Multitouch Contents
Touches with Maps