Finally, let’s do the animation! We need images of a CS student and the grim reaper. To speed things up, here are some ready-made images in the right dimensions. As you see, there’s a very specific folder structure here, telling Android Studio which images are for which display DPI (“display pixels per inch”). Again, Android Studio take care of much of this for you, and quasi-official tools like Android Asset Studio handle just about everything else.
- Download and unzip the folder into
resfolder in the zip file will be merged with the
resfolder already there, so you should end up with only one folder named
- Put an
activity_main.xmllayout. Make it display the computer worker guy (the
srcCompatattribute selects image, use the
…button to get a dialog where you can pick images from
res). Give the
ImageViewan ID, let’s say
- Note: Seems to be a bug in Android Studio making it fail to pick up the images you added. If this happens to you, File → Restart → “Invalidate caches and restart” seems to solve it. You can also switch to Text mode and enter the image reference manually, see LF.
- Add constraints at the top of the screen, the top of our “X days left” text, and the right-hand edge of the screen.
- Put another
ImageViewinto our layout. This time, select the grim reaper image. Give it an ID too, let’s say
- Add constraints: connect the top of this image to the top of the other image, bottom to bottom, and right-side to right-side. This will make the images end up on top of each other.
- Use the Margin tool at the top of the Attributes panel to set the right-hand-side margin of the reaper image to 54dp.
Note: there seems to be a bug when setting non-standard margins. If you can’t set a margin of 54, set it to one of the values from the dropdown and switch to Text view (button at bottom of designer) to update the margin to 54dp.
If you run the app now, the layout should display the reaper standing almost on top of our poor computer guy. This is the “end” of our animation. What we’ll do next, is to throw the reaper offscreen on app startup, and display an animation moving the reaper towards the user. Of course, the more hours until the deadline, the farther away the reaper should stop!
onCreate, place the grim reaper outside the left side of the screen by setting its
translationXto a large negative value (
F or more serious work you should measure how far it is to the end of the screen and how wide the view is, instead of making stupid assumptions like this.
- At the end of our
updateUImethod, we want to start the animation. In Android, the easiest way to animate a view is to call its
animate()method. Try animating the
translationXto -10f * number of hours left, and set the duration to something like three seconds. Bonus points for fancier animation!