2

I'm attempting to have my animated gif animate on loop with the following code but I'm not having any luck...

JAVA

ImageView img = (ImageView)findViewById(R.id.load_img);
img.setBackgroundResource(R.drawable.load_animation);

AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground();

frameAnimation.start();

XML

<animation-list android:oneshot="false" xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/load_0000" android:duration="50" />
<item android:drawable="@drawable/load_0001" android:duration="50" />
<item android:drawable="@drawable/load_0002" android:duration="50" />
<item android:drawable="@drawable/load_0003" android:duration="50" />
<item android:drawable="@drawable/load_0004" android:duration="50" />
<item android:drawable="@drawable/load_0005" android:duration="50" />
<item android:drawable="@drawable/load_0006" android:duration="50" />
<item android:drawable="@drawable/load_0007" android:duration="50" />
<item android:drawable="@drawable/load_0008" android:duration="50" />
<item android:drawable="@drawable/load_0009" android:duration="50" />
</animation-list>

Anyone have any idea as to why it isn't animating?

Skizit
  • 43,506
  • 91
  • 209
  • 269

3 Answers3

10

Seems that I was experiencing the same problem, when I used whether it is setImageResource(R.drawable.load_animation) or setBackgroundResource(R.drawable.load_animation), the image wasn't displaying.

then I try to put the code in my XML view file, with android:background="@drawable/load_animation got the image showed, but still not animated, it was only displaying a static image.

then after googling around a while I found that AnimationDrawable can not work in onCreate we can either put it in onResume or onWindowsFocusChanged. So here I try with this:

    public void onWindowFocusChanged(boolean hasFocus) {
    loadingAnimation = (AnimationDrawable)
    findViewById(R.id.img_loading).getBackground();
    if (hasFocus) {
        loadingAnimation.start();
    } 
    else {
        loadingAnimation.stop();
    }
}

finally it works, the gif both showed and animated!

richardlin
  • 373
  • 1
  • 5
  • 11
1

Try calling setImageResource(R.drawable.load_animation), not setBackgroundResource(R.drawable.load_animation).

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
0

i think you should use img.startxx(frameAnimation)

pengwang
  • 19,536
  • 34
  • 119
  • 168