如何将HTML模板加载到WebView中?

时间:2011-08-31 04:56:19

标签: android webview

想象一下HTML模板,如下所示:

<html>
<head>
    <style type="text/css">
        body {
            color: white;
        }
    </style>
</head>
<body>
The changes include:
<br/><br/>
%1$s
<br/><br/>
Would you like to update now?
</body>
</html>

我知道我可以使用webView.loadUrl("file:///android_asset/html/upgrade.html")将内容加载到WebView中。但我也想在运行时替换 $ 1 ,就像我使用String.format()从XML文件加载它一样。

是否可以先将文件内容加载到String中,以便我可以在其上运行String.format()然后再使用webView.loadData()

3 个答案:

答案 0 :(得分:5)

我想出了一个基于this answer to a similar question的解决方案:

String prompt = "";
AssetManager assetManager = getApplicationContext().getResources().getAssets();
try {
    InputStream inputStream = assetManager.open("html/upgrade-alert.html");
    byte[] b = new byte[inputStream.available()];
    inputStream.read(b);
    prompt = String.format(new String(b),changes);
    inputStream.close();
} catch (IOException e) {
    Log.e(LOGTAG, "Couldn't open upgrade-alert.html", e);
}

WebView html = new WebView(this);
html.loadData(prompt,"text/html","utf-8");

答案 1 :(得分:1)

只需在一些字符串中写入整个html替换一个要替换的字符串,然后使用loadData加载。

http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/WebView1.html

http://sriram-iyengar.blogspot.com/2011/05/android-webview-loaddata-and-encoding.html

类似这样的事情

答案 2 :(得分:0)

您可以使用HTMLCleaner从WebView获取HTML作为DOM并通过TagNodes进行更改。一个示例如何使用HTMLCLeaner来获取节点的某个属性。你应该在AsyncTask中执行此操作,这样它就不会阻止ui。

public static String snapFromCleanedHTMLWithXPath(String stringURL, String xPath, String attrToStrip) {
    String snap = "";

    // create an instance of HtmlCleaner
    HtmlCleaner cleaner = new HtmlCleaner();

    // take default cleaner properties
    CleanerProperties props = cleaner.getProperties();

    props.setAllowHtmlInsideAttributes(true);
    props.setAllowMultiWordAttributes(true);
    props.setRecognizeUnicodeChars(true);
    props.setOmitComments(true);

    // open a connection to the desired URL
    URL url;
    try {
        url = new URL(stringURL);
        URLConnection conn = url.openConnection();

        // use the cleaner to "clean" the HTML and return it as a TagNode object
        TagNode root = cleaner.clean(new InputStreamReader(conn.getInputStream()));

        Object[] foundNodes = root.evaluateXPath(xPath);

        if (foundNodes.length > 0) {
            // casted to a TagNode
            TagNode foundNode = (TagNode) foundNodes[0];
            snap = foundNode.getAttributeByName(attrToStrip);
        }
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (XPatherException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    cleaner = null;
    props = null;
    url = null;
    return snap;
}

HTMLCLeaner-Website