将xml加载到webView中

时间:2016-02-12 12:59:45

标签: android webview

WebView没有显示任何内容

String dataStr = new String(data, "UTF-8");
Log.d("EPAB", dataStr);
String mime = "text/html";
String encoding = "utf-8";
webView.getSettings().setJavaScriptEnabled(true);
webView.loadDataWithBaseURL(null, dataStr, mime, encoding, null);

Thera是dataStr

<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title/>
    <link rel="stylesheet" href="style.css" type="text/css"/>
    <link rel="stylesheet" href="style.css" type="text/css"/>
</head>
<body class="z">
    <span id="id1"><div class="title1">
    <p class="p">ЧАСТЬ ПЕРВАЯ</p>
    </div></span>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

尝试添加webView.setWebChromeClient(new WebChromeClient());

如果不工作将dataStr文本复制到“data.html”文件并将其保存在“Assest”上,然后加载html页面,如下所示

webView.setWebChromeClient(new WebChromeClient()); webView.loadUrl("file:///android_asset/www/data.html");

- 编辑 -

将文字发送到html文件

    String text = "" ; //text read from file
WebView webView = (WebView) findViewById(R.id.webView1);
            WebSettings webSettings = webView.getSettings();
            webSettings.setJavaScriptEnabled(true);
            webView.setWebChromeClient(new WebChromeClient());
            webView.loadUrl("file:///android_asset/www/data.html");
            webView .addJavascriptInterface(new webViewInterface(), "Data"); // Data will be used from html

在webViewInterface类

public class webViewInterface {
    private String text;

    public webViewInterface(String fileText) {
        this.text = fileText;
    }

    @JavascriptInterface
    public String getText() {
        return text;
    }
}

在data.html文件

<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title/>
    <link rel="stylesheet" href="style.css" type="text/css"/>
    <link rel="stylesheet" href="style.css" type="text/css"/>
    <script type="text/javascript">
</head>
<body class="z">
    var data = Data.getText()
    <span id="id1"><div class="title1">
    <p class="p">data</p>
    </div></span>
</body>
</html>