In android, the default control does not support images in gif format. Only the first frame of an image can be displayed. Here, the Movie class is used. Parses and plays the image. The following uses a code-only custom control, which is easy to use, but does not support components such as ImageView that can directly set attributes to set the animation to play. Here, the ID of the image under the R file is passed in through the constructor. The Code is as follows:
GifView:
Package com.home.gif; import java. io. IOException; import android. content. context; import android. graphics. canvas; import android. graphics. movie; import android. util. attributeSet; import android. view. view; public class GifView extends View {private Movie movie; private long movieStart; public GifView (Context context, AttributeSet attrs, int defStyle) {super (context, attrs, defStyle ); init (context);} public Gif View (Context context, AttributeSet attrs) {super (context, attrs); init (context);} public GifView (Context context) {super (context); init (context );} public GifView (Context context, int gifId) {super (context); init (context, gifId);} private void init (Context context) {try {movie = Movie. decodeStream (context. getAssets (). open ("loading.gif");} catch (IOException e) {e. printStackTrace () ;}} private void init (Co Ntext context, int gifId) {try {movie = Movie. decodeStream (getResources (). openRawResource (gifId);} catch (Exception e) {e. printStackTrace () ;}} public void onDraw (Canvas canvas) {long now = android. OS. systemClock. uptimeMillis (); if (movieStart = 0) {// the first frame movieStart = now;} if (movie! = Null) {int dur = movie. duration (); if (dur = 0) {dur = 1000;} int relTime = (int) (now-movieStart) % dur); movie. setTime (relTime); movie. draw (canvas, 0, 0); invalidate ();}}}
MainActivity:
package com.home.testgif;import com.home.gif.GifView;import android.os.Bundle;import android.app.Activity;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);//setContentView(new GifView(this));setContentView(new GifView(this, R.drawable.animation));}}
Note: After hardware acceleration is enabled on mobile phones of more than 4.0 of the system, GIF animation cannot be played, so we need to go to AndroidManifest. to disable hardware acceleration in xml, you can specify the android: hardwareAccelerated attribute.
android:hardwareAccelerated="false"