How to animate .gif images in an android?

Danny picture Danny · Feb 22, 2013 · Viewed 29.5k times · Source

Here is the code for xml:

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/minepic" />

Here the minepic is a gif animated image but after running the application its just showing a static image.

Is there any solution about how to animate the .gif images in android application?

Answer

Shobhit Puri picture Shobhit Puri · Nov 15, 2013

To give a precise and complete answer here is what you need to do step wise:

  1. You would need to have different .png images which will act as frames for your animation. Save them in res/drawable folder.

  2. Create anim.xml file in res/drawable folder with following content:

    <?xml version="1.0" encoding="utf-8"?>
    <animation-list xmlns:android="http://schemas.android.com/apk/res/android" 
        android:oneshot="false">
    
        <item android:drawable="@drawable/image_3" android:duration="250" />
        <item android:drawable="@drawable/image_2" android:duration="250" />
        <item android:drawable="@drawable/image_1" android:duration="250" />
        <item android:drawable="@drawable/image" android:duration="250" />
    
    </animation-list>
    
  3. In the layout xml file inside which you want to show the animation:

    //...
    <ImageView
         android:id="@+id/iv_animation"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_centerHorizontal="true"
         android:contentDescription="Animation" />
    //...
    
  4. In the Java file which loads the the layout xml file and calls setContentView:

    //...
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        final ImageView animImageView = (ImageView) findViewById(R.id.iv_animation);
        animImageView.setBackgroundResource(R.drawable.anim);
        animImageView.post(new Runnable() {
            @Override
            public void run() {
                AnimationDrawable frameAnimation =
                    (AnimationDrawable) animImageView.getBackground();
                frameAnimation.start();
            }
        });
        // ... other code ... 
    }
    // ...
    

In order to stop the animation you can call .stop() on the AnimationDrawable. For more details about the available methods, you can see AnimationDrawable documentation. Hope it helps someone.