安卓Webview加载后图片只显示一次后不再显示

4
在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 body 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。 - Zeeshan Khan
你能否将它重命名为 file:///android_asset/Learn/Images/unitcircle10.png?我知道你不能将大写字母的名称上传到drawable文件夹中,但我以前在assets文件夹中没有遇到过问题。 - bluemoon12
2个回答

2

思考了一段时间后,我解决了自己的问题。显然,网页在加载一次后会从缓存中加载,这个原因导致出现了问题 - 虽然我仍不确定为什么。我只需在加载html之前使用"w.clearCache(true);"清除缓存,现在它可以正常工作。


0

我通过使用 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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接