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

Chr*_*lay 2 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>
Run Code Online (Sandbox Code Playgroud)

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

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

Chr*_*lay 5

我基于对类似问题的答案提出了一个解决方案:

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");
Run Code Online (Sandbox Code Playgroud)