I am new to Android and I am having trouble playing an animated .gif file in the background of my layout. When I run the application the background is a single frame of the
As Martin says, Android does not support GIFs. As a workaround, Android offers Animation List/AnimationDrawable. You will need to convert the GIF into individual frames [.png files]. I use GIMP for the conversion
This GIF can be broken down into its frames:
Save them as frame01.png, frame02.png, and so on, and create an animation-list XML file, say, progress_animation.xml
<animation-list android:id="@+id/selected" android:oneshot="false">
<item android:drawable="@drawable/frame01" android:duration="50" />
<item android:drawable="@drawable/frame02" android:duration="50" />
<item android:drawable="@drawable/frame03" android:duration="50" />
....
<item android:drawable="@drawable/frameN" android:duration="50" />
To begin the animation, you need to cast the image to an AnimationDrawable, and call start() on it
AnimationDrawable progressAnimation = (AnimationDrawable) yourImageView.getBackground();
progressAnimation.start();
The gif animation is supported in Android when GIF animation is played as Movie.
Take a look.
put your gif image in app\src\main\assets
make a class like
public class MyGifView extends View {
Movie movie;
InputStream is;
long startTime;
public MyGifView(Context context) {
super(context);
try {
is = getResources().getAssets().open("anim.gif");
movie = Movie.decodeStream(is);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
super.onDraw(canvas);
long now = System.currentTimeMillis();
if (startTime == 0) // first time
startTime = now;
int relTime = (int) ((now - startTime) % movie.duration());
movie.setTime(relTime);
float scalefactorx = (float) this.getWidth() / (float) movie.width();
float scalefactory = (float) this.getHeight() / (float) movie.height();
canvas.scale(scalefactorx,1);
movie.draw(canvas, scalefactorx, scalefactory);
this.invalidate();
}
}
add a layout somewhere in your xml activity_layout (backgroundFrameLayout). Usage in your activity onCreate():
FrameLayout frameLayout = findViewById(R.id.backgroundFrameLayout);
frameLayout.addView(new MyGifView(this));