Drawable Animation: a movie made of frames

Tap the moon to make it cycle through its phases. Tap it again to stop it. See Drawable Animation and classes ImageView and AnimationDrawable. For the phases.xml file and its <animation-list> element, see Frame animation.

Source code in Phase.zip

  1. MainActivity.java
  2. R.java creates the int variables R.drawable.phases and R.drawable.phase0, R.drawable.phase1, R.drawable.phase2, etc.
  3. app/res/layout/activity_main.xml: a black RelativeLayout containing an ImageView. The ImageView has the android:background attribute.
  4. app/res/drawable/phases.xml contains a frame animation consisting of an <animation-list> containing eight <item>s.
  5. .png files in the app/res/drawable folder
    1. phase0.png 64 × 64 pixels
    2. phase1.png 64 × 64 pixels
    3. phase2.png 64 × 64 pixels
    4. phase3.png 64 × 64 pixels
    5. phase4.png 64 × 64 pixels
    6. phase5.png 64 × 64 pixels
    7. phase6.png 64 × 64 pixels
    8. phase7.png 64 × 64 pixels
  6. AndroidManifest.xml
  7. build.gradle (Module: app)

Create the project

I wanted to give the .png files the minimal names 0.png, 1.png, 2.png, etc. But I had to give them names starting with a letter or underscore because a Java identifier (variable name) has to start with one of those characters.

To copy the eight .png files into the app/res/drawable folder of your project, put the files on your Desktop. On Mac, control-click on the first file, phase0.png, and select Copy “phase0.png”. Control-click on the app/res/drawable folder in the Android Studio project view, select Paste, and press the OK button. Is there a way to copy all eight files into drawable at once?

To create the file phases.xml, select the app/res/drawable folder in the project view and pull down
File → New → Drawable resource file
New Resource File
File name: phases
OK

Things to try

  1. In phases.xml, what happens if you change android:oneshot to true? At what frame does the animation end?

  2. Remove the android:background="@drawable/phases" attribute from the ImageView element in the activity_main.xml file. Replace it with the following statement in onCreate immediately after the findViewById.
            imageView.setBackgroundResource(R.drawable.phases);
    

  3. Drawable Animation and start say that start cannot be called from onCreate. Is this true?