What are the basics of working with user input events in Android?

I thought I understood this question, but something is wrong here. When the user (I still) tries to press the keys, nothing really happens and I have problems understanding what I missed.

Think about it before presenting some code to help clarify my problem: I use the Android Lunar Lander example to make my first โ€œrealโ€ Android program. In this example, of course, there is a LunarView class and a class nested in it with LunarThread. In my code, the equivalents of these classes are Graphics and GraphicsThread, respectively.

Also I can make sprite animation in 2D just fine on Android. I have a Player class, and let GraphicsThread have a Player member called a "player." This class has four coordinates - x1, y1, x2 and y2 - and they define the rectangle in which the sprite should be drawn. I worked so that I could do a great job of this. Whenever the doDraw (Canvas canvas) method is called, it just looks at the values โ€‹โ€‹of these coordinates and draws a sprite accordingly.

Now let's say - and this is not exactly what I am trying to do with the program - I am trying to make the program where it all happens - this is to show the playerโ€™s sprite in one place on the screen until FIRST appears, the user presses the left Dpad button. Then the location will be changed to another preset position on the screen, and the sprite will be drawn in this position for the rest of the program unchanged.

Also note that the GraphicsThread element in Graphics is called "thread" and that the SurfaceHolder member in GraphicsThread is called "mSurfaceHolder".

So, consider this method in the Graphics class:

@Override public boolean onKeyDown(int keyCode, KeyEvent msg) { return thread.keyDownHandler(keyCode, msg); } 

Also consider this method in the GraphicsThread class:

 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, assuming the playerโ€™s coordinates start at (200, 200, 220, 250), why doesn't he do anything else when I press Dpad: Left?

Thanks!

+7
android user-input
source share
2 answers

Before I worry about the actual movement and the like, I would consider Log ...

Something like:

 Log.d("lunar", "keyCode = ["+String.valueOf(keyCode)+"] // msg = ["+String.valueOf(msg)+"]"); 

Thus, I can understand that the system is registering before I worry about what I am doing with the registered data ... After that, you can decide whether you really send it the right material, and then you can worry about the work of the threads etc.

Hope this helps diagnose, etc. (all this was written for free, may contain errors)

+1
source share

Drop LunarLander and use the real guide: Game with graphics in Android

0
source share

All Articles