Getting your code to load and play animated GIFs is a struggle a lot of new coders go through. It is also a topic that is heavily discussed between developers. This blog will show you a few methods that may be a solution you are looking for. This is part 2 of a 3 part series showing you 3 different ways to load animated GIFs.
Find an animated GIF and in my code examples switch your animated GIF filename with the filename I use in the code, gif betty boop glitter 108.gif. Store your GIF file in your Eclipse ASSET folder. Be sure you do this or these code examples will not work for you.
This time we will be using a new class called GifDecoder which you can download here.GifDecoder estracts the frames from the stream allowing us to use it. Place the GifDecoder file within your project src package.
Now create a new class which inherits from ImageView.But it also needs a constructor with a Context and an InputStream. We did this in part 1 of this series, but this time we will be calling the playGif(InputStream) method, as you can see we are passing it our InputStream.
Our class needs five variables.
playGif(InputStream) needs to have mGifDecoder initialized and then it will read our stream that we set as mIsPlayingGif.
Now we are going to break down our thread a bit. We will count the frames of our animation and how many times to repeat. When GifDecoder,getLoopCount() returns a 0 we know that we should play the GIF forever. GifDecoder and getFrame() are going to work hand-in-hand by trasnferring the Bitmaps images and then we will post the new Bitmap using Handler and Runnable.
The only thing left to do now is use GifDecoderView in an Activity just like we did in Part 1 of this series.
This bad boy is going to eat up a lot of memory, so don't say I didn't warn you. Always call recycle() on every Bitmap you don't need anymore. For older devices that used native heap instead of the Dalvik VM heap this method will be a big strain when used with heavy GIF files.