【问题标题】:Android webview images not showing after loading onceAndroid webview图像加载一次后不显示
【发布时间】:2015-06-04 03:16:30
【问题描述】:

在 android 中,我将带有本地图像的本地 html 加载到 webview 中。在模拟器上,甚至在我测试过的一台较新的安卓设备上,一切正常——没有问题。但是,我有一个更旧的设备(使用 android 2.3.4)有问题。当我第一次加载 html 文件时,图像显示正常。当我单击手机返回按钮,然后导航回页面时,图像消失了。我正在尝试确定这是一个常见问题还是只是旧手机的问题。

这里是加载文件:

    w = (WebView) findViewById(R.id.webview1);
    w.getSettings().setJavaScriptEnabled(true);
    w.getSettings().setBuiltInZoomControls(false);
    w.getSettings().setDefaultTextEncodingName("utf-8");

    InputStream is;
    try {
        is = getAssets().open("Learn/TrigGraphing.html");

        int size = is.available();

        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();

        String str = new String(buffer);

        w.loadDataWithBaseURL("file:///android_asset/Learn/Images/", str, "text/html", "utf-8", "file:///android_asset/Learn/TrigGraphing.html");

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

这里是html:

<img id="img03" class="images" src="file:///android_asset/Learn/Images/UnitCircle10.png"/>

还有一个转折点——如果图像太大而无法在屏幕上显示,我会调整它们的大小。这主要用于平板电脑。在 html 正文 onload() 函数上,我执行以下 javascript:

function checkImgSize() {
if($(document).width() > $(window).width()) {

    windowWidth = $(window).width();

    var elements = document.getElementsByClassName("images");
    for (var i=0; i<elements.length; i++) {

        currentImgWidth = elements[i].width;
        currentImgHeight = elements[i].height;

        newImgWidth = Math.round(0.85*windowWidth);
        newImgHeight = (newImgWidth/currentImgWidth)*currentImgHeight;

        elements[i].style.width = newImgWidth;
        elements[i].style.height = newImgHeight;

    }
}

我查看了此调整大小功能,但我不明白为什么如果图像第二次加载它会使图像消失,但我不确定。有人有什么建议吗?

【问题讨论】:

  • 图片名使用小写的html文件如abc.png
  • 喜欢重命名它的文件:///android_asset/Learn/Images/unitcircle10.png?我知道您不能将大写名称上传到 drawables 文件夹中,但我之前在 assets 文件夹中没有遇到问题

标签: java javascript android html webview


【解决方案1】:

我通过使用 css background 属性而不是 img 标签解决了我的问题。

而不是这个:

<img width="100" height="100" class="images" src="file:///android_asset/Learn/Images/UnitCircle10.png"/>

我用过这个:

<div style="width: 100px; height: 100px; background:url(file:///android_asset/Learn/Images/UnitCircle10.png); background-size:cover; "></div>

【讨论】:

    【解决方案2】:

    我想了一会儿解决了自己的问题。显然,网页在加载一次后从缓存中加载,出于某种原因,这搞砸了——尽管我仍然不确定为什么。我刚刚用“w.clearCache(true);”清除了缓存在加载 html 之前,它现在可以正常工作了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多