Write and sell Android apps with Basic 4 Android: Part 2
As before, we click Add Images to load our spaceship, and adjust the Image file property of the ImageView to display it. We’ve used an image editor to give the graphic a transparent background, so it sits neatly on top of the playfield, and saved our layout under the name “spaceship-layout”. Now it’s time to return to the editor and create the necessary code to make the spaceship move. Here’s what we’ve come up with:
As this code illustrates, animations in B4A are objects. They’re configured via methods and properties, and activated using the Start method, passing the target object as a parameter. We’ve used the InitializeTranslate method to set up a lateral movement, but with other methods we could animate the alpha (opacity), scale and rotation of our spaceship. These tools are all found in B4A’s external Animation library, so if you want to compile this program for yourself, you’ll need to add a reference to it. To do this, click to activate the Libs panel at the right of the B4A window and tick “Animation”.
When you try running this code you’ll immediately see that, in Android, animated objects return to their original position once the animation is complete. In our program, the spaceship repeatedly moves away from its original location then jumps back to its original position. Happily, this problem can be easily fixed as follows:
When an animation completes, an AnimationEnd event is raised, which we can check for with a regular event-handling sub. Within this sub, we use the SetLayout method to immediately move the spaceship to the position where the animation ended. To the user, it appears that the spaceship has moved to its destination and stayed there.
Finally, this program also illustrates the use of timers to trigger events. When the program first runs – that is, when the main activity is created – we set up a timer for one second (the parameter is in milliseconds) and enable it. Since our animation is set to last for 750 milliseconds, the result is a spaceship that moves, hesitates briefly, then moves again.
The program continues to run until externally terminated, but you could easily add elements to give the user more control, such as allowing him or her to adjust or suspend the timer. Alternatively, you could create an event handler for playArea_Touch, and program the spaceship to home in on the user’s finger when the screen is tapped.
Handling multiple orientations
Our flying saucer program sits neatly on the screen in portrait mode, but if you turn your phone on its side – or press Ctrl-F11 to rotate your AVD into landscape mode – the orientation changes and suddenly the play area doesn’t fit on the screen any more. All the views keep their original positioning, relative to the top-left corner of the screen, but effectively, the screen itself changes shape.