添加自定义CSS为HTML code与jsoup [英] Add custom css to html code with jsoup

查看:521
本文介绍了添加自定义CSS为HTML code与jsoup的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个Android应用程序,它加载一个HTML页面,并显示在一个web视图。 问题是我想补充我的自定义的CSS(加载的HTML还没有任何CSS或链接到一个CSS)。如何添加使用jsoup自定义CSS到HTML code? 我不能修改HTML。 又是如何的web视图可以随后打开呢? 谢谢

I'm working on an Android app, which loads a HTML page and shows it in a webview. The problem is I want to add my custom css (the loaded HTML hasn't any CSS or link to a css). How do I add the custom css to the HTML code using jsoup? I cant modify the html. And how does the webview can open it afterwards? Thank you

推荐答案

几个方面。您可以使用<一个href="http://jsoup.org/apidocs/org/jsoup/nodes/Element.html#append%28java.lang.String%29"><$c$c>Element#append()追加一些HTML的一部分的元素。

Several ways. You can use Element#append() to append some piece of HTML to the element.

Document document = Jsoup.connect(url).get();
Element head = document.head();
head.append("<link rel=\"stylesheet\" href=\"http://example.com/your.css\">");

或者使用<一个href="http://jsoup.org/apidocs/org/jsoup/nodes/Element.html#attr%28java.lang.String,%20java.lang.String%29"><$c$c>Element#attr(name,值) 添加属性到现有元素。下面是它增加了风格=一个例子颜色:粉红色;来的所有链接

Document document = Jsoup.connect(url).get();
Elements links = document.select("a");
links.attr("style", "color:pink;");

无论哪种方式,修改后获得通过<一个最终的HTML字符串href="http://jsoup.org/apidocs/org/jsoup/nodes/Element.html#html%28%29"><$c$c>Document#html().

String html = document.html();

它写到file <一个href="http://developer.android.com/reference/java/io/PrintWriter.html#write%28java.lang.String%29"><$c$c>PrintWriter#write() (用正确的字符集)。

Write it to file by PrintWriter#write() (with the right charset).

String charset = Jsoup.connect(url).response().charset();
// ...
Writer writer = new PrintWriter("/file.html", charset);
writer.write(html);
writer.close();

最后,在web视图中打开它。既然不能从头顶告诉它,在这里只是一个与我认为这是有帮助的一个例子链接:<一href="http://$c$c.google.com/p/apps-for-android/source/browse/trunk/Samples/WebViewDemo/src/com/google/android/webviewdemo/WebViewDemo.java">WebViewDemo.java.我发现链接这个博客的方式(我又被谷歌发现)。

Finally open it in the webview. Since I can't tell it from top of head, here's just a link with an example which I think is helpful: WebViewDemo.java. I found the link on this blog by the way (which I in turn found by Google).

这篇关于添加自定义CSS为HTML code与jsoup的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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