Display Animated GIF

后端 未结 30 2545
无人及你
无人及你 2020-11-22 02:11

I want to display animated GIF images in my aplication. As I found out the hard way Android doesn\'t support animated GIF natively.

However it can display animations

30条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 02:50

    also put (main/assets/htmls/name.gif) [with this html adjust to the size]

    
    
    
    
    
    

    declare in your Xml for example like this (main/res/layout/name.xml): [you define the size, for example]

    
    

    in your Activity put the next code inside of onCreate

    web = (WebView) findViewById(R.id.webView); 
    web.setBackgroundColor(Color.TRANSPARENT); //for gif without background
    web.loadUrl("file:///android_asset/htmls/name.html");
    

    if you want load dynamically you have to load the webview with data:

    // or "[path]/name.gif" (e.g: file:///android_asset/name.gif for resources in asset folder), and in loadDataWithBaseURL(), you don't need to set base URL, on the other hand, it's similar to loadData() method.
    String gifName = "name.gif";
    String yourData = "\n" +
            "    \n" +
            "    \n" +
            "    \n" +
            "    ";
    // Important to add this attribute to webView to get resource from outside.
    webView.getSettings().setAllowFileAccess(true);
    
    // Notice: should use loadDataWithBaseURL. BaseUrl could be the base url such as the path to asset folder, or SDCard or any other path, where your images or the other media resides related to your html
    webView.loadDataWithBaseURL("file:///android_asset/", yourData, "text/html", "utf-8", null);
    // Or if you want to load image from SD card or where else, here is the idea.
    String base = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
    webView.loadDataWithBaseURL(base + '/', yourData, "text/html", "utf-8", null);
    

    suggestion: is better load gif with static images for more information check https://developer.android.com/reference/android/graphics/drawable/AnimationDrawable.html

    That's it, I hope you help.

提交回复
热议问题