Game Development Reference
In-Depth Information
The
KeyEvent
class is similar to the
MotionEvent
class. It has two methods that are relevant
for us:
ï?®
KeyEvent.getAction()
: This returns
KeyEvent.ACTION_DOWN
,
KeyEvent.ACTION_UP
,
and
KeyEvent.ACTION_MULTIPLE
. For our purposes, we can ignore the last
key event type. The other two will be sent when a key is either pressed or
released.
ï?®
KeyEvent.getUnicodeChar()
: This returns the Unicode character the key
would produce in a text field. Say we hold down the Shift key and press
the A key. This would be reported as an event with a key code of
KeyEvent.KEYCODE_A
, but with a Unicode character
A
. We can use this
method if we want to do text input ourselves.
To receive keyboard events, a
View
must have the focus. This can be forced with the following
method calls:
View.setFocusableInTouchMode(true);
View.requestFocus();
The first method will guarantee that the
View
can be focused. The second method requests that
the specific
View
gets the focus.
Let's implement a simple test activity to see how this works in combination. We want to get key
events and display the last one we received in a
TextView
. The information we'll display is the
key event type, along with the key code and the Unicode character, if one would be produced.
Note that some keys do not produce a Unicode character on their own, but only in combination
with other characters. Listing 4-5 demonstrates how we can achieve all of this in a small number
of code lines.
Listing 4-5. KeyTest.Java; Testing the Key Event API
package
com.badlogic.androidgames;
import
android.app.Activity;
import
android.os.Bundle;
import
android.util.Log;
import
android.view.KeyEvent;
import
android.view.View;
import
android.view.View.OnKeyListener;
import
android.widget.TextView;
public class
KeyTest
extends
Activity
implements
OnKeyListener {
StringBuilder builder =
new
StringBuilder();
TextView textView;
public
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
textView =
new
TextView(
this
);
textView.setText("Press keys (if you have some)!");
textView.setOnKeyListener(
this
);