使用自定义 CSS 在 WebView 中呈现 HTML [英] Rendering HTML in a WebView with custom CSS

查看:25
本文介绍了使用自定义 CSS 在 WebView 中呈现 HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序正在使用 JSoup 下载留言板页面的 HTML(假设在这种情况下它是一个包含给定线程帖子的页面).我想采用此 HTML,去除不需要的项目,并应用自定义 CSS 将其设置为 WebView 中的移动"样式.

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 时将样式注入到 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 文件,则不需要指定基本网址.

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

这篇关于使用自定义 CSS 在 WebView 中呈现 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆