2

我的html字符串是这样的:

<meta http-equiv=\"Content-Type\" content=\"text/html\"; charset=\"UTF-8\" />
<p style="text-align: justify;"> paragraph </p>
<p style="text-align: justify;"> another one with <strong> strong attr </p>
<p style="text-align: justify;"> in general p have <strong> strong</strong> and <em> em parts</em></p>

我加载:

view.loadData(htmlString, "text/html", "UTF-8");

我有不同的 html 字符串,其中一些没问题,但其他人给我这个错误......问题出在哪里?

4

3 回答 3

3

解决了,给我很多“帮助”这个答案,因为它真的是一个讨厌的 webview 错误,我认为我的回答会对你们很多人有帮助!

如果您的 html 页面确实包含“%”、“\”或“#”字符之一,则 loadData() 方法将失败!因此,您必须手动替换这些 chr,这是我的课程:

public class BuglessWebView extends WebView{

public BuglessWebView(Context context) {
    super(context);
}

public BuglessWebView(Context context,AttributeSet attributes){
    super(context,attributes);
}

public BuglessWebView(Context context,AttributeSet attributes,int defStyles){
    super(context,attributes,defStyles);
}

@Override
public void loadData(String data, String mimeType, String encoding) {

    super.loadData(solveBug(data), mimeType, encoding);
}

private String solveBug(String data){
    StringBuilder sb = new StringBuilder(data.length()+100);
    char[] dataChars = data.toCharArray();

    for(int i=0;i<dataChars.length;i++){
        char ch = data.charAt(i);
        switch(ch){
        case '%':
            sb.append("%25");
            break;
        case '\'':
            sb.append("%27");
            break;
        case '#':
            sb.append("%23");
            break;
        default:
            sb.append(ch);
            break;
        }
    }

    return sb.toString();
}
}

这是关于谷歌代码的讨论链接: http ://code.google.com/p/android/issues/detail?id=1733

于 2012-09-08T18:47:16.597 回答
3

请改用 loadDataWithBaseURL。

 webView.loadDataWithBaseURL(null, html,"text/html", "UTF-8", null);

这是具有此解决方法的讨论: http ://code.google.com/p/android/issues/detail?id=1733

评论:#14 和#18

在这里工作。

于 2013-06-25T19:38:33.527 回答
1

我刚刚遇到了这个问题,并且有很多相关的错误报告与它有关。我有一个 % 是我的内联 CSS,导致页面没有被渲染。当我在文档中看到时,我认为一切都很好WebView.loadData(...)

encoding 参数指定数据是 base64 还是 URL 编码。如果数据是base64编码的,编码参数的值必须是'base64'。对于参数的所有其他值(包括 null),假定数据对安全 URL 字符范围内的八位字节使用 ASCII 编码,并对超出该范围的八位字节使用 URL 的标准 %xx 十六进制编码。例如, '#', '%', '\', '?' 应分别替换为 %23、%25、%27、%3f。

但唉,base64按照指示使用没有任何区别。在我的 4.3 设备上一切都很好,但在 2.3 上什么都不会渲染。查看所有错误报告,每个人都提出了不同的建议,但唯一对我有用的是使用

webView.loadDataWithBaseURL(null, data.content, "text/html", "UTF-8", null);

小心不要使用text/html;text/html因为它会默默地失败!

于 2013-12-03T16:31:21.130 回答