1

I added aa animated GIF file in android xml layout,with no java handler but the gif is not playing. The following method was accepted as a solution in one of the related question.

gradle

 dependencies {
        implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.+'
    } 

layout

<pl.droidsonroids.gif.GifTextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:scaleX="1.05"
                android:scaleY="0.9"
                android:background="@drawable/for_op" />
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Ved Sarkar
  • 251
  • 2
  • 8
  • 25

4 Answers4

2

FYI

If drawables declared by android:src and/or android:background are GIF files then they will be automatically recognized as GifDrawables and animated. If given drawable is not a GIF then Views work like plain ImageView. I already Noticed that.

NOTE

You should use latest version 1.2.12 instead of adding +.

dependencies {
    compile 'pl.droidsonroids.gif:android-gif-drawable:1.2.12'
}
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
1

First Make a class GifView

   import android.annotation.SuppressLint;
   import android.content.Context;
   import android.graphics.Canvas;
   import android.graphics.Movie;
   import android.os.Build;
   import android.util.AttributeSet;
   import android.view.View;


     public class GIFView extends View {

     private static final int DEFAULT_MOVIEW_DURATION = 1000;
     private int mMovieResourceId;
     private Movie mMovie;
     int movieWidth;
     int movieHeight;
     private long mMovieStart = 0;
     private int mCurrentAnimationTime = 0;

     @SuppressLint("NewApi")
     public GIFView(Context context, AttributeSet attrs) {
     super(context, attrs);

    /**
     * Starting from HONEYCOMB have to turn off HardWare acceleration to draw
     * Movie on Canvas.
     */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }
}

public void setImageResource(int mvId){
    this.mMovieResourceId = mvId;
    int w=500;

    mMovie = Movie.decodeStream(getResources().openRawResource(mMovieResourceId));

    requestLayout();
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if(mMovie != null){
        setMeasuredDimension(mMovie.width(), mMovie.height());
        movieWidth = mMovie.width();
        movieHeight = mMovie.height();
    }else{
        setMeasuredDimension(getSuggestedMinimumWidth(), getSuggestedMinimumHeight());
    }
}

@Override
protected void onDraw(Canvas canvas) {
    if (mMovie != null){
        updateAnimtionTime();
        drawGif(canvas);
        invalidate();
    }else{
        drawGif(canvas);
    }
}

private void updateAnimtionTime() {
    long now = android.os.SystemClock.uptimeMillis();

    if (mMovieStart == 0) {
        mMovieStart = now;
    }
    int dur = mMovie.duration();
    if (dur == 0) {
        dur = DEFAULT_MOVIEW_DURATION;
    }
    mCurrentAnimationTime = (int) ((now - mMovieStart) % dur);
}
public int getMovieWidth() {
    return movieWidth;
}

public int getMovieHeight() {
    return movieHeight;
}
private void drawGif(Canvas canvas) {
    mMovie.setTime(mCurrentAnimationTime);
    mMovie.draw(canvas, 0,0);
    canvas.scale(0f, 0f);

    canvas.restore();
}
}

Then Declare This Thing in xml

    <yourpackagename.GIFView
    android:layout_width="match_parent"
    android:id="@+id/gif"
    android:layout_gravity="center"
    android:layout_height="100dp"
      />

Then Finally in Activity

    GIFView gif;
    gif =(GIFView) findViewById(R.id.gif);
    gif.setImageResource(R.drawable.loading); // your loading gif
1

First you should implement this library.

implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.7'

Now in xml file add this code.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_splash_screen"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <pl.droidsonroids.gif.GifTextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/logo" />

</RelativeLayout>

Now in Activity implement delay to show gif animation time to show.

 int time = 4000;

      new Handler().postDelayed(new Runnable()
            {
                @Override
                public void run()
                {
                   startActivity(new Intent(SplashScreen.this, YourActivity.class));
                }
            }, time);
Ramchandra Singh
  • 530
  • 4
  • 15
0

You can also use Glide as it is officially supported by google for loading images,gifs etc with efficient memory management. I would suggest you to use the same, As I used it before and it worked perfectly for me.

Check it here https://github.com/bumptech/glide

Adding it to Gradle:

repositories {
  mavenCentral()
  google()
}

dependencies {
  implementation 'com.github.bumptech.glide:glide:4.7.1'
  annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1'
}

How to use it for loading Gifs:

Glide.with(this).load(R.raw.file.gif)
                    .crossFade()
                    .dontAnimate()
                    .into(new GlideDrawableImageViewTarget(imageView) {
                        @Override
                        public void onLoadStarted(Drawable placeholder) {
                            super.onLoadStarted(placeholder);
                           //DO your loader related stuff here
                        }

                        @Override
                        public void onResourceReady(GlideDrawable drawable, GlideAnimation anim) {
                            super.onResourceReady(drawable, anim);
                            //Close loader here 
                              imageView.setImageDrawable(drawable);
                          } 

                        @Override
                        public void onLoadFailed(Exception e, Drawable errorDrawable) {
                            super.onLoadFailed(e, errorDrawable);
                            //Close loader and set error placeholder here.

                            imageView.setImageResource(R.drawable.ic_home_image_placeholder);
                        }
                    });

Also for checking that your file is gif or not you can use method shared below:

private int getResourceType(String assetName) {
        int id = 0;
        if (assetName != null && !assetName.trim().isEmpty()) {
            int start = assetName.indexOf(".");
            int end = assetName.length();
            if(start >= 0 && end <= assetName.length()) {
                String type = assetName.substring(assetName.indexOf("."), assetName.length());
                if (type != null && type.equalsIgnoreCase(".gif")) {
                    id = 1;
                } else if(type != null && (type.equalsIgnoreCase(".png") || type.equalsIgnoreCase(".jpg")
                        || type.equalsIgnoreCase(".jpeg"))) {
                    id = 2;
                } else {
                    id = 0;
                }
            }
        }
        return id;
    }
Rishabh Saxena
  • 1,765
  • 15
  • 26