Handling User Interaction Events

In order for your new View to be interactive, it will need to respond to user events like key presses, screen touches, and button clicks. Android exposes several virtual event handlers, listed here, that let you react to user input:

> onKeyDown Called when any device key is pressed; includes the D-pad, keyboard, hang-up, call, back, and camera buttons

> onKeyUp Called when a user releases a pressed key

> onTrackballEvent Called when the device's trackball is moved

> onTouchEvent Called when the touchscreen is pressed or released, or when it detects movement

Listing 4-14 shows a skeleton class that overrides each of the user interaction handlers in a View.

LISTING 4-14: Input event handling for Views Available for download on ©Override

Wrax.com public boolean onKeyDown(int keyCode, KeyEvent keyEvent) { // Return true if the event was handled. return true;

©Override public boolean onKeyUp(int keyCode, KeyEvent keyEvent) { // Return true if the event was handled. return true;

©Override public boolean onTrackballEvent(MotionEvent event ) { // Get the type of action this event represents int actionPerformed = event.getAction(); // Return true if the event was handled. return true;

@Override public boolean onTouchEvent(MotionEvent event) { // Get the type of action this event represents int actionPerformed = event.getAction(); // Return true if the event was handled. return true;

Further details on using each of these event handlers, including greater detail on the parameters received by each method and support for multitouch events, are available in Chapter 15.

Mobile Apps Made Easy

Mobile Apps Made Easy

Quick start guide to skyrocket your offline and online business success with mobile apps. If you know anything about mobile devices, you’ve probably heard that famous phrase coined by one of the mobile device’s most prolific creators proclaiming that there’s an app for pretty much everything.

Get My Free Training Guide


Post a comment