2011-02-09 63 views
65

我的應用程序使用JSoup來下載留言板頁面的HTML(假設這是一個包含給定線程帖子的頁面)。我想採用這種HTML,去除不需要的項目,並應用自定義CSS來將其設置爲WebView中的「移動」。使用自定義CSS在WebView中呈現HTML

我應該在HTML中處理樣式時注入樣式(因爲我會處理它)還是有一種很好的方法來將CSS文件添加到我的應用程序的資產並簡單地引用它。我認爲後者是理想的,但不確定如何去做。

我在WebView的loadDataWithBaseURL中看到提示,提示您可以引用本地資源,但不知道如何使用它。

回答

103

你可以使用WebView.loadDataWithBaseURL

htmlData = "<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" />" + htmlData; 
// lets assume we have /assets/style.css file 
webView.loadDataWithBaseURL("file:///android_asset/", htmlData, "text/html", "UTF-8", null); 

並且只有經過網頁視圖將能夠找到,從固定資產使用CSS-文件目錄。

ps並且,是的,如果您從資產文件夾加載html文件,則不需要指定基本url。

+9

謝謝!那正是我需要的。 (順便說一句,你可以在內聯HTML中使用單引號而不是雙引號;這樣你就不需要反斜槓了。總是看起來有點整齊......) – 2012-01-06 17:57:19

+1

不錯。我會把PS作爲直接的答案:如果你使用WebView.loadUrl(「file:///android_asset/fname.html」)加載你的html文件;你可以簡單地使用它內的相關網址。 – fortboise 2014-01-31 23:19:49

0

是否有可能在給定的div中顯示所有頁面內呈現的內容?然後你可以重新設置基於id的css,並從那裏開始工作。

說你給你的DIV ID = 「OCON」

在你的CSS,有這樣一個定義:

#ocon *{background:none;padding:0;etc,etc,} 

,你可以設置值從申請內容清除所有的CSS。 之後,你可以只使用

#ocon ul{} 

或什麼的,再往下的樣式,新樣式應用到的內容。

18

這裏是解決

把你的HTML和CSS在你的/資產/文件夾,然後加載HTML文件,如下所示:

WebView wv = new WebView(this); 

    wv.loadUrl("file:///android_asset/yourHtml.html"); 

然後在你的HTML,你可以參考你的CSS中通常的方式

<link rel="stylesheet" type="text/css" href="main.css" /> 
8

就這麼簡單,就是:

WebView webview = (WebView) findViewById(R.id.webview); 
webview.loadUrl("file:///android_asset/some.html"); 

而且你some.html需要包含類似:

<link rel="stylesheet" type="text/css" href="style.css" /> 
32

我假設你的風格表「風格。CSS」已經位於資產文件夾

  1. 負載的網頁與jsoup:

    doc = Jsoup.connect("http://....").get(); 
    
  2. 刪除鏈接到外部樣式表:

    // remove links to external style-sheets 
    doc.head().getElementsByTag("link").remove(); 
    
  3. 集鏈接到本地​​樣式表:

    // set link to local stylesheet 
    // <link rel="stylesheet" type="text/css" href="style.css" /> 
    doc.head().appendElement("link").attr("rel", "stylesheet").attr("type", "text/css").attr("href", "style.css"); 
    
  4. 從jsoup-DOC /網頁
  5. 製作繩:

    String htmldata = doc.outerHtml(); 
    
  6. 顯示網頁中的WebView:

    WebView webview = new WebView(this); 
    setContentView(webview); 
    webview.loadDataWithBaseURL("file:///android_asset/.", htmlData, "text/html", "UTF-8", null); 
    
0

如果你在內部文件中存儲你的CSS你可以使用

//Get a reference to your webview 
WebView web = (WebView)findViewById(R.id.webby); 

// Prepare some html, it is formated with css loaded from the file style.css 
String webContent = "<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><link rel=\"stylesheet\" href=\"style.css\"></head>" 
         + "<body><div class=\"running\">I am a text rendered with INDIGO</div></body></html>"; 

//get and format the path pointing to the internal storage 
String internalFilePath = "file://" + getFilesDir().getAbsolutePath() + "/"; 

//load the html with the baseURL, all files relative to the baseURL will be found 
web.loadDataWithBaseURL(internalFilePath, webContent, "text/html", "UTF-8", "");