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
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));