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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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

396<br />

}<br />

}<br />

}<br />

for (int i = 0; i < historySize; i++) {<br />

float x = event.getHistoricalX(i);<br />

float y = event.getHistoricalY(i);<br />

processMovement(x, y);<br />

}<br />

float x = event.getX();<br />

float y = event.getY();<br />

processMovement(x, y);<br />

return true;<br />

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

private void processMovement(float _x, float _y) {<br />

// Todo: Do something on movement.<br />

}<br />

Android includes two excellent examples of using the touch screen in the Fingerpaint and<br />

Touch Paint API Demos.<br />

Using the OnTouchListener<br />

You can listen for touch events without subclassing an existing View by attaching an OnTouchListener<br />

to any View object, using the setOnTouchListener method. The following code snippet demonstrates<br />

how to assign a new OnTouchListener implementation to an existing View within an Activity:<br />

myView.setOnTouchListener(new OnTouchListener() {<br />

});<br />

public boolean onTouch(View _view, MotionEvent _event) {<br />

// TODO Respond to motion events<br />

return false;<br />

}<br />

Using the Device Keys and Buttons (Including D-Pad)<br />

Button and key-press events for all hardware keys are handled by the onKeyDown and onKeyUp handlers<br />

of the active Activity or the focused view. This includes keyboard keys, D-pad, volume, back, dial,<br />

and hang-up buttons. The only exception is the Home key, which is reserved to ensure that users can<br />

never get locked within an application.<br />

To have your View or Activity react to button presses, override the onKeyUp and onKeyDown event handlers<br />

as shown in the following skeleton code:<br />

@Override<br />

public boolean onKeyDown(int _keyCode, KeyEvent _event) {<br />

// Perform on key pressed handling, return true if handled

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

Saved successfully!

Ooh no, something went wrong!