想象一下这样一个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.format(),然后改用webView.loadData()

最佳答案

我想出了一个基于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");

10-05 21:15
查看更多