What are the basics of dealing with user input events in Android?
- by user279112
Hello. I thought I had understood this question, but something is quite wrong here. When the user (me, so far) tries to press keys, nothing really happens, and I am having a lot of trouble understanding what it is that I've missed.
Consider this before I present some code to help clarify my problem: I am using Android's Lunar Lander example to make my first "real" Android program. In that example, of course, there exist a class LunarView, and class nested therein LunarThread. In my code the equivalents of these classes are Graphics and GraphicsThread, respectively.
Also I can make sprite animations in 2D just fine on Android. I have a Player class, and let's say GraphicsThread has a Player member referred to as "player". This class has four coordinates - x1, y1, x2, and y2 - and they define a rectangle in which the sprite is to be drawn. I've worked it out so that I can handle that perfectly. Whenever the doDraw(Canvas canvas) method is invoked, it'll just look at the values of those coordinates and draw the sprite accordingly.
Now let's say - and this isn't really what I'm trying to do with the program - I'm trying to make the program where all it does is display the Player sprite at one location of the screen UNTIL the FIRST time the user presses the Dpad's left button. Then the location will be changed to another set position on the screen, and the sprite will be drawn at that position for the rest of the program invariably.
Also note that the GraphicsThread member in Graphics is called "thread", and that the SurfaceHolder member in GraphicsThread is called "mSurfaceHolder".
So consider this method in class Graphics:
@Override
public boolean onKeyDown(int keyCode, KeyEvent msg) {
return thread.keyDownHandler(keyCode, msg);
}
Also please consider this method in class GraphicsThread:
boolean keyDownHandler(int keyCode, KeyEvent msg) {
synchronized (mSurfaceHolder) {
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
player.x1 = 100;
player.y1 = 100;
player.x2 = 120;
player.y2 = 150;
}
}
return true;
}
Now then assuming that player's coordinates start off as (200, 200, 220, 250), why won't he do anything different when I press Dpad: Left?
Thanks!