How to play a GIF file in Android?

2019-03-21 05:25发布

问题:

I want to play a GIF file in my current activity.

I have an XML file in which there is a layout.

I want to play the GIF in the same class Activity.

Is there a simple way to play a GIF file in an Activity class?

回答1:

Android doesn't support the playing of animated GIF files. If you need to play them then you need to break them apart into frames, and animate each frame one by one.

This will let you split up the GIF file http://www.xoyosoft.com/gs/



回答2:

You can use a webView. I will show with an example:

//My activity
public class Gift_Loading extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Gif_loading_View view = new Gif_loading_View(this); 
        setContentView(view);
    }

}

//the webView
public class Gif_loading_View extends WebView{

    public Gif_loading_View(Context context) {

        super(context);     
        loadUrl("file:///android_asset/loading_position.html");

        } 
}

In the assets folder add this html file:

<html>
<body bgcolor="white">
    <table width="100%" height="100%">
        <tr>
            <td align="center" valign="center">                
                <br/>
                <br/>
                <br/>
                <font size="6">Please wait...</font>
                <br/>
                <br/>
                <img src="cyclist_loading.gif" />

            </td>
        </tr>
    </table>
</body>


回答3:

There's an example here in which a custom AnimatedGifView class is created.

It makes use of the android.graphics.Movie class, and overrides the onDraw method to redraw the view periodically. Here's an excerpt:

gifInputStream = context.getResources().openRawResource(R.drawable.myGIFImage);
gifMovie = Movie.decodeStream(gifInputStream);
gifMovie.setTime((int)movieRunDuration);
gifMovie.draw(canvas, 0, 0);

It's probably more appropriate to convert animated GIFs to AnimationDrawables, instead, however.



回答4:

<pl.droidsonroids.gif.GifTextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/first"
    />

Use the code and your gif file put into the drawable folder.... and change the name first with your gif file name.