14.01.2013 Views

Android™ Application Development - Bahar Ali Khan

Android™ Application Development - Bahar Ali Khan

Android™ Application Development - Bahar Ali Khan

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 11: Advanced Android <strong>Development</strong><br />

394<br />

Finger-based touch makes interaction less precise and is often based more on movement than simple<br />

contact. Android’s native applications make extensive use of fi nger-based touch-screen interfaces,<br />

including the use of dragging motions to scroll lists or perform actions.<br />

To create a View or Activity that uses touch-screen interaction, override the onTouchEvent handler as<br />

shown in the skeleton code below:<br />

@Override<br />

public boolean onTouchEvent(MotionEvent event) {<br />

return super.onTouchEvent(event);<br />

}<br />

Return true if you have handled the screen press; otherwise, return false to pass events through a<br />

stack of Views and Activities until the touch has been successfully handled.<br />

Processing Touch Events<br />

The onTouchEvent handler is fi red when the user fi rst touches the screen, once each time the position<br />

changes, and again when the contact ends.<br />

The action property of the MotionEvent parameter refl ects which of these event types has triggered<br />

the handler. To determine the initiating touch action, call getAction on the Motion Event parameter,<br />

and compare it to the static MotionEvent action values, as shown in the following skeleton code:<br />

@Override<br />

public boolean onTouchEvent(MotionEvent event) {<br />

}<br />

int action = event.getAction();<br />

switch (action) {<br />

case (MotionEvent.ACTION_DOWN) : // Touch screen pressed<br />

break;<br />

case (MotionEvent.ACTION_UP) : // Touch screen touch ended<br />

break;<br />

case (MotionEvent.ACTION_MOVE) : // Contact has moved across screen<br />

break;<br />

case (MotionEvent.ACTION_CANCEL) : // Touch event cancelled<br />

break;<br />

}<br />

return super.onTouchEvent(event);<br />

The Motion Event also includes the coordinates of the current screen contact. You can access these<br />

coordinates using the getX and getY methods. These methods return the coordinate relative to the<br />

responding View or Activity; alternatively, getRawX and getRawY return the absolute screen coordinates.<br />

Both techniques are shown in the following code snippet:<br />

// Relative screen coordinates.<br />

int xPos = (int)event.getX();<br />

int yPos = (int)event.getY();

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!