How to display gif on Android device [duplicate]

2019-08-31 00:38发布

问题:

This question already has an answer here:

  • Display Animated GIF 29 answers

I'm trying to display gif images on Android. I found this code on SO, which is said a correct solution by some users :

webView wView = new webView(this);    
wView.loadUrl("file:///android_asset/piggy.gif"); 
setContentView(view);

It says my gif file should be in assets folder. What should I do if my gif file is in drawable folder? And shouldn't the last line be like this :

setContentView(wView);

Other than this, if you have an easy solution for displaying gifs on Android, I can accept. Thanks.

回答1:

Android has some basic requirements. All .gif / videos and custom fonts or (.otf) files must be only placed in assets folder. There is no other way of doing it as far as I know. To access the asset's files you have write a line of code :

The Format to access the Resource is as follows:

    "android.resource://[package]/[res id]"

    Uri myUri =("android.resource://" + context.getPackageName() + "/"
                        + R.drwable.mygifimage);
    try{
        Url myUrl = myUri.toURL();
        webView wView = new webView(this);   
        wView.loadUrl(myUrl);
        setContentView(view);

       }catch(Exception e){
              e.printStackTrace()
       }