Estimated reading time: 2 minutes
Posted on February 7, 2012

Android & How to Use Animated Gifs

The Android platform currently supports quite a large number of media formats. See the documentation here. Among the described graphic file formats you’ll find the one we are interested in – GIF.

In general, help me write my essay this format does not cause any troubles until you try to animate it. In this case, the standard class ImageView displays a GIF file as a regular static image. If researching related forums, you’ll probably find people claiming that the

Android platform doesn’t fully support GIF and animated GIFs cannot be used.

Nevertheless, you can still solve this problem and I’ll show you the loophole.

There are at least two ways:

It is difficult to say what solution is better, however, there is one important point. Although a WebView is a part of any Android SDK, the ability to play animated GIF files is only available starting from version Android 2.2 (API level 8). So if you aim at supporting a wide range of devices, the second option is, perhaps, more acceptable for you.

It wouldn’t be completely fair to say that the class Movie is well documented. In such a case, this article would probably be useless :-)

So let’s try to create a separate component that can play animated GIF files using the Movie-class.

OK, creating a new class GIFView inheriting from View:

Now we add a new variable of the Movie type to our class and initialize it:

OK, now our Movie-object is initialized and we just need to draw it. We will use the onDraw(Canvas) method for this purpose, but before that we need to let the Movie-object know what part of the GIF file to draw. To do this, we need a separate variable movieStart of the long type, to which we assign the SystemClock.uptimeMillis() value. In this case, we will know when the movie has started and can calculate how much time has passed.

All we need now is to initialize the GIFView in our Activity class.

Now let’s add a possibility to pass the GIF id as a parameter.

Here is how the Activity class should look like:

Another good practice is using XML markup components. So let’s try this as well. For this purpose I’ll create a file attrs.xml (res/values/attrs.xml) with the following structure:

Now we just need to read XML attributes in our GIFView class:

We are able to use the GIFView in XML markup the following way:

Our Activity class looks like this:

And that’s really it! If you have ever used such an approach or have a better solution, please let us know.