2012-05-29 38 views
2

我正在顯示一個帶有遠程html內容的webview作爲字符串從遠程服務器獲取。 我在本地存儲了一個沒有連接使用我的應用程序的HTML。使用本地css和js在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> 

我加載使用

this.webView.loadDataWithBaseURL(getFilesDir().getAbsolutePath(), html, "text/html", "utf-8", "about:blank"); 
的HTML

但是風格和js都沒有考慮到,所以我認爲我們的路徑出了問題e引用它們,或加載webView。那麼怎麼做呢?我發現許多使用「資產」文件夾的答案,但我不想使用它,因爲我必須從服務器更新css和js。

回答

3

最後,我已經找到了解決辦法:

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:

    • 的CSS(或JS)文件使用此方法保存在本地使用文件

      <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");

  • 相關問題