我正在显示一个带有远程html内容的webview,从远程服务器获取字符串。 我在本地存储了html,无法连接我的应用程序。
此外,我还在本地存储.js脚本和.css样式文件。这些文件可以由服务器更新。
我将所有这些文件存储在以下路径中:
context.getFilesDir()+"content.css"
context.getFilesDir()+"content.js"
在html字符串中,css和js的引用如下:
<link rel="stylesheet" href="/content.css" type="text/css" media="screen">
<script src="/content.js"></script>
我使用
加载htmlthis.webView.loadDataWithBaseURL(getFilesDir().getAbsolutePath(), html, "text/html", "utf-8", "about:blank");
但是没有考虑样式和js,所以我认为用于引用它们或加载webView的路径有问题。那么这样做的方法是什么?我找到了许多使用“assets”文件夹的答案,但我不想使用它,因为我必须从服务器更新css和js。
答案 0 :(得分:3)
最后我找到了解决方案:
使用此方法将css(或js)文件保存在本地:
public static void writeToFile(Context context, String content, String title) throws IOException
{
OutputStreamWriter osw = new OutputStreamWriter(context.openFileOutput(title,Context.MODE_WORLD_READABLE));
osw.write(content);
osw.close();
}
然后我使用
在html文件中引用它 <link rel="stylesheet" href="content.css" type="text/css" media="screen">
<script src="content.js"></script>
最后我使用以下方式打开了webview:
this.webView = (WebView) findViewById(R.id.webview);
this.webView.getSettings().setJavaScriptEnabled(true);
this.webView.getSettings().setPluginsEnabled(true);
this.webView.setHorizontalScrollBarEnabled(false);
this.webView.setVerticalScrollBarEnabled(true);
this.webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
this.webView.setWebViewClient(this.controller.getWebViewClient());
String basePath = "file://"+getFilesDir().getAbsolutePath()+"/";
this.webView.loadDataWithBaseURL(basePath, data, "text/html", "utf-8", "about:blank");