How to load an animated gif on Android

1

There are libraries to load animated gifs within an application, but what would be the proper way to load animated gifs without using third-party libraries or custom views?

GifImageView

GifView

GifMovieView

I had done loading .gif using WebView in this way:

   WebView webView =  (WebView)findViewById(R.id.webView);
   webView = (WebView) findViewById(R.id.webView);
   webView.loadUrl("file:///android_asset/myanimation.gif");

But you also want the .gif to be in a url and not within the resources of the project.

    
asked by Elenasys 26.04.2018 в 23:15
source

2 answers

1

There are two options for loading animated gifs in an Android application. using these methods you can load animated gifs from a url.

1) Using Glide to load the animated gif within ImageView .

    String urlGif = "https://domain.com/myanimatedgif.gif";
    //Agregar implementacion Glide dentro de archivo build.gradle.
    ImageView imageView = (ImageView)findViewById(R.id.imageView);
    Uri uri = Uri.parse(urlGif);
    Glide.with(getApplicationContext()).load(uri).into(imageView);

2) Using an html to load the animated gif within WebView .

Create an html that contains the path to the .gif file:

<html style="margin: 0;">
<body style="margin: 0;">
<img src="https://..../myimage.gif" style="width: 100%; height: 100%" />
</body>
</html>

store this .html file inside the /assets directory:

Now load the html within WebView in your application:

    WebView webView =  (WebView)findViewById(R.id.webView);
    webView = (WebView) findViewById(R.id.webView);
    webView.loadUrl("file:///android_asset/html/webpage_gif.html");

Here is a full example showing both options .

    
answered by 26.04.2018 / 23:15
source
1

In your gradle file in the dependencies part add:

implementation 'com.github.bumptech.glide:glide:4.7.1'

And in the part of java where he is reading the image he places

if(isGif(dirImagen)){
    Glide.with(getApplicationContext()).asGif().load(dirImagen).into(imga);
}
else{
    Glide.with(getApplicationContext()).load(dirImagen).into(imga);
}

private boolean isGif(String imagen) {
    String extension = "";
    int i = imagen.lastIndexOf('.');
    int p = Math.max(imagen.lastIndexOf('/'), imagen.lastIndexOf('\'));
    if (i > p) {
        extension = imagen.substring(i+1);
    }
    return extension.trim().equalsIgnoreCase("gif");
}

It is asked if it is gif to improve the load, by not reading the gif as gif these delay in showing on the screen.

    
answered by 26.04.2018 в 23:33