In this third installment of the Android Game Development series, I’ll try to explain how to construct the project. I know the LunaLander sample directly uses thread and SurfaceHolder.Callback, but my first goal is simply to display an image, I will complexify later.
Games don’t use Views
In Android, most of the games don’t really use the View hierarchy of objects, because it’s too slow and cumbersome. They instead write directly to a Canvas.
In order to get the Canvas displayed to the screen, you create a SurfaceView object.
Thus, the page is a FrameLayout, and inside we put our SurfaceView class, as shown in the main resource file:


How to insert an Image into Android project ?
Using Gimp, I have drawn a small red ball:
Nice isn’t it ? 
How can I use it in my project. Well it’s quite simple, you copy the file in your project res/drawable subdirectory, you update your Eclipse Project (F5 key). Automagically, you see your new image in the project, and the Eclipse Plugin regenerates the R class so that you can easily access the resource in your code or Layout file. Just take a look at this sample (called by the constructor of our SurfaceView):

We can now easily override the onDraw method on our SurfaceView derived class, and display the image:


Notice we set the position and dimension to display in the image itself, and tells it to display into the canvas. I would have expected the other way round (calling a Canvas method to draw the image).
I run the project and here is the result :


Well something got wrong, but what ? Maybe I should check in Android documentation how to see some sort of logs or whatever, but for now, each time I get this, I’m clueless about what went wrong.
This time it was easy, I put the wrong class name in the layout.xml file, and it couldn’t find my SurfaceView class. Too bad Eclipse didn’t warn me about this. I fixed the error, started again, and then:
A Black screen. No Error but no red ball neither….
Running it under debugger shows me that the onDraw method on my SurfaceView class is not called !
After some more experiments, (checked the LunarLander sample, tried to draw a big green square on Canvas, etc….) I finally managed to make it work.
To have the SurfaceView displayed, you have to set a background color. With my init method like that:

I get the « good » result as follow: Yeepeee !!!


GC.