Game Development Reference
In-Depth Information
public KeyEvent createObject() {
return new KeyEvent();
}
};
keyEventPool= new Pool<KeyEvent>(factory, 100);
view.setOnKeyListener( this );
view.setFocusableInTouchMode( true );
view.requestFocus();
}
The constructor has a single parameter consisting of the View from which we want to receive key
events. We create the Pool instance with a proper PoolObjectFactory , register the handler as
an OnKeyListener with the View , and, finally, make sure that the View will receive key events by
making it the focused View .
public boolean onKey(View v, int keyCode, android.view.KeyEvent event) {
if (event.getAction() == android.view.KeyEvent. ACTION_MULTIPLE )
return false ;
synchronized ( this ) {
KeyEvent keyEvent=keyEventPool.newObject();
keyEvent.keyCode=keyCode;
keyEvent.keyChar=( char ) event.getUnicodeChar();
if (event.getAction() == android.view.KeyEvent. ACTION_DOWN ) {
keyEvent.type=KeyEvent. KEY_DOWN ;
if (keyCode>0 && keyCode<127)
pressedKeys[keyCode]= true ;
}
if (event.getAction() == android.view.KeyEvent. ACTION_UP ) {
keyEvent.type=KeyEvent. KEY_UP ;
if (keyCode>0 && keyCode<127)
pressedKeys[keyCode]= false ;
}
keyEventsBuffer.add(keyEvent);
}
return false ;
}
Next, we will discuss our implementation of the OnKeyListener.onKey() interface method, which
is called each time the View receives a new key event. We start by ignoring any (Android) key
events that encode a KeyEvent.ACTION_MULTIPLE event. These are not relevant in our context.
This is followed by a synchronized block. Remember, the events are received on the UI thread
and read on the main loop thread, so we have to make sure that none of our members are
accessed in parallel.
Within the synchronized block, we first fetch a KeyEvent instance (of our KeyEvent
implementation) from the Pool . This will either get us a recycled instance or a brand-new one,
depending on the state of the Pool . Next, we set the KeyEvent 's keyCode and keyChar members
based on the contents of the Android KeyEvent that were passed to the method. Then, we
decode the Android KeyEvent type and set the type of our KeyEvent , as well as the element
in the pressedKey array, accordingly. Finally, we add our KeyEvent to the previously defined
keyEventBuffer list.
Search WWH ::




Custom Search