Game Development Reference
In-Depth Information
textView.setFocusableInTouchMode( true );
textView.requestFocus();
setContentView(textView);
}
public boolean onKey(View view, int keyCode, KeyEvent event) {
builder.setLength(0);
switch (event.getAction()) {
case KeyEvent. ACTION_DOWN :
builder.append("down, ");
break ;
case KeyEvent. ACTION_UP :
builder.append("up, ");
break ;
}
builder.append(event.getKeyCode());
builder.append(", ");
builder.append(( char ) event.getUnicodeChar());
String text = builder.toString();
Log. d ("KeyTest", text);
textView.setText(text);
return event.getKeyCode() != KeyEvent. KEYCODE_BACK ;
}
}
We start off by declaring that the activity implements the OnKeyListener interface. Next, we
define two members with which we are already familiar: a StringBuilder to construct the text to
be displayed and a TextView to display the text.
In the onCreate() method, we make sure the TextView has the focus so it can receive key
events. We also register the activity as the OnKeyListener via the TextView.setOnKeyListener()
method.
The onKey() method is also pretty straightforward. We process the two event types in the
switch statement, appending a proper string to the StringBuilder . Next, we append the key
code as well as the Unicode character from the KeyEvent itself and output the contents of the
StringBuffer instance to LogCat as well as the TextView .
The last if statement is interesting: if the Back key is pressed, we return false from the
onKey() method, making the TextView process the event. Otherwise, we return true . Why
differentiate here?
If we were to return true in the case of the Back key, we'd mess with the activity life cycle a little.
The activity would not be closed, as we decided to consume the Back key ourselves. Of course,
there are scenarios where we'd actually want to catch the Back key so that our activity does not
get closed. However, it is strongly advised not to do this unless absolutely necessary.
Figure 4-8 illustrates the output of the activity while holding down the Shift and A keys on the
keyboard of a Droid.
Search WWH ::




Custom Search