search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Table of Contents
1. Environment preparation
2. Preliminary implementation of GIF single playback
3. Core solution: Use animation end callback
4. Precautions and Best Practices
Summarize
Home Java javaTutorial Android Glide: Implement GIF playback once and then automatically convert to static image display

Android Glide: Implement GIF playback once and then automatically convert to static image display

Dec 31, 2025 am 02:12 AM

Android Glide: Implement GIF playback once and then automatically convert to static image display

This tutorial explains in detail how to use the Glide library in Android applications to automatically switch and display GIF animations as static images after playing once. By utilizing Glide's animation callback mechanism, developers can precisely control the life cycle of a GIF and seamlessly load and display its corresponding static image when the animation ends, thereby improving user experience and optimizing resource management.

In Android application development, GIF animation is widely used because of its lively characteristics. However, in some scenarios, we may need the GIF animation to play only once, and then automatically switch and display as a static picture after the animation ends, instead of looping infinitely or disappearing directly. For example, a loading animation, a one-time special effects display, etc. This article will guide you how to use the powerful image loading library Glide to elegantly implement this function.

1. Environment preparation

First, make sure the Glide library is configured correctly in your Android project. Add the following dependencies in your build.gradle (module level) file:

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

Next, define an ImageView in your layout file to display the animated GIF and subsequent static image:

 <imageview android:id="@ id/fuse" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginstart="4dp" android:layout_marginleft="4dp" android:padding="8dp" android:src="@drawable/fuseev4"></imageview>

Here, @drawable/fuseev4 is your GIF resource file (for example, a file named fuseev4.gif).

2. Preliminary implementation of GIF single playback

To achieve single playback of GIF, we can use Glide's listener callback and GifDrawable's setLoopCount() method.

 import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.vectordrawable.graphics.drawable.Animatable2Compat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;

public class GifDisplayActivity extends AppCompatActivity {

    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Suppose you have a layout file activity_gif_display.xml that contains an ImageView with the id fuse
        setContentView(R.layout.activity_gif_display);
        imageView = findViewById(R.id.fuse);

        // Example trigger point, such as playing a GIF on button click
        findViewById(R.id.play_gif_button).setOnClickListener(view -&gt; playGifOnceAndTransition());
    }

    private void playGifOnceAndTransition() {
        Glide.with(this)
                .asGif()
                .load(R.drawable.fuseev4) // Your GIF resource.apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE)) // It is generally recommended to disable disk caching of GIFs to ensure that each load is complete.listener(new RequestListener<gifdrawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<gifdrawable> target, boolean isFirstResource) {
                        // Handling when GIF loading fails if (e != null) {
                            e.printStackTrace();
                        }
                        return false; // Return false to let Glide continue processing errors}

                    @Override
                    public boolean onResourceReady(GifDrawable resource, Object model, Target<gifdrawable> target, DataSource dataSource, boolean isFirstResource) {
                        // Callback resource.setLoopCount(1) when the GIF resource is ready; // Set the GIF to play only once // Directly loading static images here is invalid because the GIF animation has not yet ended // Glide.with(GifDisplayActivity.this).asBitmap().load(R.drawable.fuseev4).into(imageView);
                        return false; // Return false to let Glide set the resource to Target
                    }
                })
                .into(imageView);
    }
}</gifdrawable></gifdrawable></gifdrawable>

In the above code, we call resource.setLoopCount(1) in the onResourceReady callback, which indeed allows the GIF to play only once. However, if you try to load the static image immediately in onResourceReady, or perform static image loading immediately after the GIF loading code block (such as the afterListeners() method in the original question), you will find that the static image will be displayed immediately instead of waiting for the GIF animation to finish playing. This is because onResourceReady is triggered when the GIF animation starts playing, and the subsequent static image loading code will be executed almost at the same time, unable to wait for the animation to complete.

3. Core solution: Use animation end callback

To solve the above problem, we need a mechanism to listen to the end event of GIF animation. Glide's GifDrawable provides a registerAnimationCallback() method, which, combined with Animatable2Compat.AnimationCallback, can accurately execute the logic we need after the animation is played.

Modify the onResourceReady method and add animation callback:

 @Override
public boolean onResourceReady(GifDrawable resource, Object model, Target<gifdrawable> target, DataSource dataSource, boolean isFirstResource) {
    resource.setLoopCount(1); // Set the GIF to play only once // Register the animation end callback resource.registerAnimationCallback(new Animatable2Compat.AnimationCallback() {
        @Override
        public void onAnimationEnd(Drawable drawable) {
            super.onAnimationEnd(drawable);
            // After the GIF animation is played, load the static image Glide.with(GifDisplayActivity.this)
                    .asBitmap() // Load as bitmap (static image)
                    .load(R.drawable.fuseev4) // Your static image resource, usually uses the same resource ID as GIF
                    .into(imageView);
        }
    });
    return false; // Return false to let Glide set the resource to Target
}</gifdrawable>

Complete sample code:

Integrate the above modifications into GifDisplayActivity. A complete implementation is as follows:

 import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.vectordrawable.graphics.drawable.Animatable2Compat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;

public class GifDisplayActivity extends AppCompatActivity {

    private ImageView imageView;
    private Button playGifButton; // Assume there is a button to trigger GIF play @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gif_display); // Your layout file imageView = findViewById(R.id.fuse);
        playGifButton = findViewById(R.id.play_gif_button); // Assume there is a button with the id play_gif_button in the layout playGifButton.setOnClickListener(view -&gt; playGifOnceAndTransition());
    }

    private void playGifOnceAndTransition() {
        // Clear the previous image first to ensure that the GIF can be fully displayed imageView.setImageDrawable(null); 

        Glide.with(this)
                .asGif()
                .load(R.drawable.fuseev4) // Your GIF resource.apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE)) // Disable the GIF's disk cache and ensure it is reloaded every time.listener(new RequestListener<gifdrawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<gifdrawable> target, boolean isFirstResource) {
                        if (e != null) {
                            e.printStackTrace();
                        }
                        // When loading fails, you can also choose to load a default static image Glide.with(GifDisplayActivity.this)
                             .asBitmap()
                             .load(R.drawable.default_static_image) // Assume there is a default static image.into(imageView);
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GifDrawable resource, Object model, Target<gifdrawable> target, DataSource dataSource, boolean isFirstResource) {
                        resource.setLoopCount(1); // Set the GIF to play only once // Register the animation end callback resource.registerAnimationCallback(new Animatable2Compat.AnimationCallback() {
                            @Override
                            public void onAnimationEnd(Drawable drawable) {
                                super.onAnimationEnd(drawable);
                                // After the GIF animation is played, load the static image Glide.with(GifDisplayActivity.this)
                                        .asBitmap() // Load as bitmap (static image)
                                        .load(R.drawable.fuseev4) // Your static image resource.into(imageView);
                            }
                        });
                        return false;
                    }
                })
                .into(imageView);
    }
}</gifdrawable></gifdrawable></gifdrawable>

In activity_gif_display.xml you may want to add a button to trigger:

 <?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center" tools:context=".GifDisplayActivity">

    <imageview android:id="@ id/fuse" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:layout_marginstart="4dp" android:layout_marginleft="4dp" android:padding="8dp" android:src="@drawable/fuseev4"></imageview> <!-- The first frame or placeholder image of the GIF can be displayed initially -->

    <button android:id="@ id/play_gif_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Play GIF" android:layout_margintop="16dp"></button>

</linearlayout>

4. Precautions and Best Practices

  • Resource consistency: Usually, you will want to display the static image corresponding to the last frame of the GIF after the GIF animation ends. The easiest way is to load the static image using the same resource ID as the GIF. When Glide loads a GIF, if the GIF contains static frames, it can also extract the first frame as a placeholder, or load a static representation of the GIF during asBitmap().
  • Cache Strategy: When loading a GIF, RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE) is a common choice to ensure that each time the GIF is loaded, it starts from scratch, rather than reading from cache that may have already been played. But for subsequently loaded static images, you can consider using the default caching strategy to improve efficiency.
  • Memory management: Animated GIFs generally take up more memory than static images. Make sure your GIF file size is appropriate and manage the ImageView lifecycle properly to avoid memory leaks.
  • Error handling: In the onLoadFailed callback, you can handle the situation when GIF loading fails, such as displaying a default static image or error message.
  • UI thread: The onAnimationEnd callback is executed on the UI thread, so you can update the UI directly there (such as loading a new image).
  • Cancel callback: If your Activity or Fragment is destroyed before the GIF animation ends, it is best to cancel Glide's request in onDestroy() to avoid potential crashes or memory leaks.

Summarize

By utilizing Glide's RequestListener and GifDrawable's registerAnimationCallback() method, we can precisely control the number of times the GIF animation plays and seamlessly replace it with a static image after the animation ends. This method provides a high degree of flexibility, making it simple and efficient to implement complex GIF animation interactions in Android applications, greatly improving the user experience.

The above is the detailed content of Android Glide: Implement GIF playback once and then automatically convert to static image display. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to configure Spark distributed computing environment in Java_Java big data processing How to configure Spark distributed computing environment in Java_Java big data processing Mar 09, 2026 pm 08:45 PM

Spark cannot run in local mode, ClassNotFoundException: org.apache.spark.sql.SparkSession. This is the most common first step of getting stuck: even the dependencies are not correct. Only spark-core_2.12 is written in Maven, but spark-sql_2.12 is not added. SparkSession crashes as soon as it is built. The Scala version must strictly match the official Spark compiled version - Spark3.4.x uses Scala2.12 by default. If you use spark-sqljar of 2.13, the class loader cannot directly find the main class. Practical advice: Go to mvnre

How to safely map user-entered weekday string to integer value and implement date offset operation in Java How to safely map user-entered weekday string to integer value and implement date offset operation in Java Mar 09, 2026 pm 09:43 PM

This article introduces a concise and maintainable way to map the weekday string (such as "Monday") to the corresponding serial number (1-7), and use the modulo operation to realize the forward and backward offset of any number of days (such as Monday plus 4 days to get Friday), avoiding lengthy if chains and hard-coded logic.

What is exception masking (Suppressed Exceptions) in Java_Multiple resource shutdown exception handling What is exception masking (Suppressed Exceptions) in Java_Multiple resource shutdown exception handling Mar 10, 2026 pm 06:57 PM

What is SuppressedException: It is not "swallowed", but actively archived by the JVM. SuppressedException is not an exception loss, but the JVM quietly attaches the secondary exception to the main exception under the premise that "only one exception must be thrown" for you to verify afterwards. It is automatically triggered by the JVM in only two scenarios: one is that the resource closure in try-with-resources fails, and the other is that you manually call addSuppressed() in finally. The key difference is: the former is fully automatic and safe; the latter requires you to keep it to yourself, and it can be written as shadowing if you are not careful. try-

How to use Homebrew to install Java on Mac_A must-have Java tool chain for developers How to use Homebrew to install Java on Mac_A must-have Java tool chain for developers Mar 09, 2026 pm 09:48 PM

Homebrew installs the latest stable version of openjdk (such as JDK22) by default, not the LTS version; you need to explicitly execute brewinstallopenjdk@17 or brewinstallopenjdk@21 to install the LTS version, and manually configure PATH and JAVA_HOME to be correctly recognized by the system and IDE.

How to correctly implement runtime file writing in Java applications (avoiding JAR internal write failures) How to correctly implement runtime file writing in Java applications (avoiding JAR internal write failures) Mar 09, 2026 pm 07:57 PM

After a Java application is packaged as a JAR, data cannot be written directly to the resources in the JAR package (such as test.txt) because the JAR is essentially a read-only ZIP archive; the correct approach is to write variable data to an external path (such as a user directory, a temporary directory, or a configuration-specified path).

What is the underlying principle of array expansion in Java_Java memory dynamic adjustment analysis What is the underlying principle of array expansion in Java_Java memory dynamic adjustment analysis Mar 09, 2026 pm 09:45 PM

ArrayList.add() triggers expansion because grow() is called when size is equal to elementData.length. The first add allocates 10 capacity, and subsequent expansion is 1.5 times and not less than the minimum requirement, relying on delayed initialization and System.arraycopy optimization.

Complete tutorial on reading data from file and initializing two-dimensional array in Java Complete tutorial on reading data from file and initializing two-dimensional array in Java Mar 09, 2026 pm 09:18 PM

This article explains in detail how to load an integer sequence in an external text file into a Java two-dimensional array according to a specified row and column structure (such as 2500×100), avoiding manual assignment or index out-of-bounds, and ensuring accurate data order and robust and reusable code.

A concise method in Java to compare whether four byte values ​​are equal and non-zero A concise method in Java to compare whether four byte values ​​are equal and non-zero Mar 09, 2026 pm 09:40 PM

This article introduces several professional solutions for efficiently and safely comparing multiple byte type return values ​​(such as getPlayer()) in Java to see if they are all equal and non-zero. We recommend two methods, StreamAPI and logical expansion, to avoid Boolean and byte mis-comparison errors.

Related articles