To date Android platform supports a sufficiently large number of media formats. See documentation here. Among the declared graphic formats you’ll find the one we are interested – GIF. Generally speaking this format does not cause any difficulties until you’ll try to use a GIF file with animation. In this case, the standard class ImageView displays GIF file as a usual static image. Doing search you can find forums stating that Android platform doesn’t fully support GIF, that animated GIF files cannot be used. Nevertheless you can still solve this problem and I’ll show you how.
There are at least two ways:
It is difficult to say which solution is better, however there is one important point. Although WebView is a part of any Android SDK, the ability to play animated GIF files only appeared from version Android 2.2 (API level 8). So if you plan support for vide range of devices, then second option is likely more acceptable for you. I’ll further focus on it.
It is not quite fair to say that class Movie is well documented. Otherwise, this article probably would be useless :-) So, let’s try to create a separate component that can play animated GIF files using class Movie.
OK, creating a new class GIFView, inherited from View:
Now let’s add new variable of type Movie to our class and initialize it
OK, now Movie object is initialized and we just need to draw it. We will use onDraw(Canvas) method for this purpose, but before that, we must let Movie object know what exact part of GIF file it should draw. To do this we need a separate variable movieStart of long type, which we assign SystemClock.uptimeMillis() value. In this case we will know when the movie was started and can calculate how much time has passed.
All we need now is initialize GIFView in our Activity class
Now let’s add the possibility to pass GIF id as a parameter
Here is how the Activity class should look:
Another good practice is using components in XML markup. So, let’s also do this. For this purpose I’ll create file attrs.xml (res/values/attrs.xml) with the following structure:
Now we just need to read XML-attributes in our GIFView class:
After this we are able to use GIFView in XML markup the following way:
Our Activity class looks the following way:
That’s it. Have you ever used such approach or maybe you have some better solution – please let us know.