Game Development Reference
In-Depth Information
This class simply defines two constants that encode the key event type along with three
members while holding the type, key code, and Unicode character of the event. With this, we
can implement our handler.
Listing 5-8 shows the implementation of the handler with the Android APIs discussed earlier and
our new
Pool
class. The listing is broken up by commentary.
Listing 5-8. KeyboardHandler.java: Handling Keys Since 2010
package
com.badlogic.androidgames.framework.impl;
import
java.util.ArrayList;
import
java.util.List;
import
android.view.View;
import
android.view.View.OnKeyListener;
import
com.badlogic.androidgames.framework.Input.KeyEvent;
import
com.badlogic.androidgames.framework.Pool;
import
com.badlogic.androidgames.framework.Pool.PoolObjectFactory;
public class
KeyboardHandler
implements
OnKeyListener {
boolean
[] pressedKeys=
new boolean
[128];
Pool<KeyEvent>keyEventPool;
List<KeyEvent>keyEventsBuffer=
new
ArrayList<KeyEvent>();
List<KeyEvent>keyEvents=
new
ArrayList<KeyEvent>();
The
KeyboardHandler
class implements the
OnKeyListener
interface so that it can receive key
events from a
View
. The members are next.
The first member is an array holding 128 Booleans. We store the current state (pressed or not)
of each key in this array. It is indexed by the key's key code. Luckily for us, the
android.view.
KeyEvent.KEYCODE_XXX
constants (which encode the key codes) are all between 0 and 127, so
we can store them in a garbage collector-friendly form. Note that by an unlucky accident, our
KeyEvent
class shares its name with the Android
KeyEvent
class, of which instances get passed
to our
OnKeyEventListener.onKeyEvent()
method. This slight confusion is only limited to this
handler code. As there's no better name for a key event than “
KeyEvent
,� we chose to live with
this short-lived confusion.
The next member is a
Pool
that holds the instances of our
KeyEvent
class. We don't want to
make the garbage collector angry, so we recycle all the
KeyEvent
objects we create.
The third member stores the
KeyEvent
instances hat have not yet been consumed by our game.
Each time we get a new key event on the UI thread, we add it to this list.
The last member stores the
KeyEvent
s that we return by calling the
KeyboardHandler.getKeyEvents()
. In the following sections, we'll see why we have to
double-buffer the key events.
public
KeyboardHandler(View view) {
PoolObjectFactory<KeyEvent>factory=
new
PoolObjectFactory<KeyEvent>() {