I have been messing around with the Snake example code and I am trying to mod this for the sake of training, and hopefully increased understanding of how Android works.
So far I have added two buttons + the corresponding setOnClickListener code as per below.
snake_layout.xml:
<Button
android:layout_height="39px"
android:layout_width="55px"
android:layout_marginLeft="15px"
android:text="Left"
android:id="@+id/left_button" />
<Button
android:layout_height="39px"
android:layout_width="55px"
android:layout_marginLeft="240px"
android:text="Right"
android:id="@+id/right_button" />
and Snake.java:
.
.
.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// No Title bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.snake_layout);
final Button leftButton = (Button) findViewById(R.id.left_button);
leftButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v)
{
//perform action
}
});
final Button rightButton = (Button) findViewById(R.id.right_button);
rightButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v)
{
//perform action
}
});
.
.
.
Both buttons show up where they are supposed to and work when I try a simple method, such as "finish()".
Now, what I would like to do is to have these buttons trigger the code below, in SnakeView.java:
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
if (mDirection != EAST) {
mNextDirection = WEST;
}
return (true);
}
if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
if (mDirection != WEST) {
mNextDirection = EAST;
}
return (true);
}
To be clear, I need to have my custom on-screen buttons performing the same job as "KEYCODE_DPAD_RIGHT" and "KEYCODE_DPAD_LEFT" in the current code. My Xperia X10i doesn't come with a DPAD, that's part of it ;-P
I would really appreciate some pointers in the right direction. As you might have guessed I'm fairly new to this..
Thanks in advance guys
Check here:
Throwing/Simulating KeyStrokes programatically
The basic logic is hidden behind:
private void doInjectKeyEvent(KeyEvent kEvent) {
try {
/* Inject the KeyEvent to the Window-Manager. */
windowManager.injectKeyEvent(kEvent.isDown(), kEvent.getKeyCode(),
kEvent.getRepeatCount(), kEvent.getDownTime(),
kEvent.getEventTime(), true);
} catch (DeadObjectException e) {
e.printStackTrace();
}
}
In place of // perform action in your onClick methods, copy the appropriate body from the existing code (e.g., if (mDirection != EAST) mNextDirection = WEST;).
As an aside, it is considered poor practice to specify button dimensions in pixels. This does not work well for code intended to run on devices that may have very different pixel densities and screen sizes. It's much better to let the buttons size themselves based on what they contain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With