【问题标题】:android- load gif animation in webviewandroid- 在 webview 中加载 gif 动画
【发布时间】:2021-10-13 02:44:09
【问题描述】:

我正在WebView 中显示一个 gif 文件。

此 gif 在我的网页加载完成之前可见。

我是通过以下方式来做的:

第一种方法:在 Webview 中加载 gif

我已将loading.gif 放入asset 文件夹中。

xml:

<WebView
    android:id="@+id/webview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="2dp"
    android:layout_centerHorizontal="true"/>

Java:

wv.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            WebView loading = (WebView)findViewById(R.id.webview1);
            loading.loadUrl("file:///android_asset/loading.GIF");
            loading.setBackgroundColor(Color.TRANSPARENT);
            loading.setVisibility(View.VISIBLE);
        }
        @Override
        public void onPageFinished(WebView view, String url) {
            WebView loading = (WebView)findViewById(R.id.webview1);
            loading.setVisibility(View.INVISIBLE);
        }

    });

第二种方法:在 ImageView 中加载 gif 帧

xml:

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="true">
    <item android:drawable="@drawable/frame1" android:duration="50" />
    <item android:drawable="@drawable/frame2" android:duration="50" />
    <item android:drawable="@drawable/frame3" android:duration="50" />
    etc...
</animation-list>

Java:

imageView.setBackgroundResource(R.drawable.movie);
AnimationDrawable anim = (AnimationDrawable) imageView.getBackground();
anim.start();

但是这两种情况下的动画都不流畅。不过,第二种方法更好。我只是想知道有没有什么方法可以在没有gif的情况下达到同样的效果?如果那不可能,我想知道 gif 是否在所有像素密度中都具有相同的大小。因为gif文件的尺寸在px而不是dp

【问题讨论】:

  • 你用什么来加载 gif 图片???您如何看待 Glide Google 库...对于 gif Webview 或 Glide,哪种方法更好?
  • 您不需要加载帧,只需在 WebView 或 ImageView 中加载动画 gif,我已经添加了答案。

标签: android animation webview


【解决方案1】:

这是一个例子

如何将 gif 加载到 WebView

使用 .gif 文件的地址创建 html:

<html style="margin: 0;">
<body style="margin: 0;">
<img src="https://..../myimage.gif" style="width: 100%; height: 100%" />
</body>
</html>

将此文件存储到资产目录中:

将此 html 加载到您的应用程序的 WebView 中:

    WebView webView =  (WebView)findViewById(R.id.webView);
    webView = (WebView) findViewById(R.id.webView);
    webView.loadUrl("file:///android_asset/html/webpage_gif.html");

这是complete example with two options (using WebView or ImageView) to load an animated gif

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    • 2018-08-12
    • 2013-11-13
    相关资源
    最近更新 更多