在一个web视图自定义CSS渲染HTML

问题描述:

我的应用程序正在使用JSoup下载留言板网页的HTML(比方说,在这种情况下,它是一个页面,其中包含一个指定线程的职位)。我想借此HTML,去掉不需要的物品,并应用自定义CSS样式它是移动的web视图。

My app is using JSoup to download the HTML of a message board page (let's say in this case it is a page containing the posts of a given thread). I'd like to take this HTML, strip out unwanted items, and apply custom CSS to style it to be 'mobile' in a WebView.

我应该注入样式到HTML,因为我处理它(因为我无论如何都会被处理),或者是有一个CSS文件添加到我的应用程序的资产,只是指它的好方法。我想,后者将是理想的,但不知道该如何去做。

Should I inject the styles into the HTML as I process it (since I will be processing it anyway) or is there a good way to add a CSS file to my app's assets and simply refer to it. I figure the latter would be ideal, but unsure how to go about it.

我看到的WebView的提示loadDataWithBaseURL你可以参照当地的资产,但不知道如何利用它。

I see hints in WebView's loadDataWithBaseURL that you can refer to local assets, but not sure how to utilize it.

您可以使用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);

和只有在那之后的WebView将能找到并使用CSS-文件从资产目录。

And only after that WebView will be able to find and use css-files from the assets directory.

PS是的,如果您将HTML文件形成的资产的文件夹,你并不需要指定一个基本URL。

ps And, yes, if you load your html-file form the assets folder, you don't need to specify a base url.