这是一个古老且已被接受的问题,但是我确信可以通过使用 javascript 以更优雅的方式解决该问题。
将 html 文件保存在您的 asset 文件夹中,并用具有唯一 id 的 div 元素将要替换的文本包围起来。
<html>
<head> ... <head>
<body>
Static text
<div id="replace1">replace me</div>
<div id="replace2">replace me too</div>
More static text ...
</body>
</html>
现在创建一个 javascript 函数,它将用一个 div 替换 innerHtmlid:
function replace(id, newContent)
{
document.getElementById(id).innerHTML = newContent;
}
这个函数最好直接放在html文件中,更新一下<head>
部分看起来像这样:
<head>
...
<script type="text/javascript">
function replace(id, newContent)
{
document.getElementById(id).innerHTML = newContent;
}
</script>
</head>
现在我们需要从 WebView Android api 调用 javascript 函数:
WebView helpView = (WebView)findViewById(R.id.helpView);
helpView.getSettings().setJavaScriptEnabled(true);
helpView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:replace('replace1', 'new content 1')");
view.loadUrl("javascript:replace('replace2', 'new content 2')");
}
});
helpView.loadUrl("file:///android_asset/help.html");
使用此功能,您将避免将潜在的大数据读入内存并对其运行不必要的昂贵操作。