设置WebView字体颜色,背景颜色

来源:互联网 发布:freemind软件使用方法 编辑:程序博客网 时间:2024/04/30 06:42

上次总结了一下WebView更改字体大小的帖子,这次在加点料,索性把webView的字体颜色和背景颜色都设置一下。   现在的App大多数支持日夜间模式的切换,对于新闻阅读类的App,更改WebView的日夜间模式,显得尤为重要。更改字体颜色,主要的思想是在WebView加载的Data的外面,加载了一个模板,然后根据用户日夜间模式切换的点击事件,更改WebView的字体颜色。其实这里例子懂了之后,以后对于WebView的界面处理,就简单很多。都是加载模板,更改里面的内容。有的服务器返回的data格式,在手机上显得很格格不入,那样的话就需要,在处理后的data上,再加一个正则表达式的过滤了,详细需要过滤的,还得根据不同情况,查询不同的过滤规则。言归正传,先说说这个更改字体颜色的核心代码。

private String initContent(String content, boolean night, boolean flag) {try {InputStream inputStream = getResources().getAssets().open("discover.html");BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream), 16 * 1024);StringBuilder sBuilder = new StringBuilder();String line = null;while ((line = reader.readLine()) != null) {sBuilder.append(line + "\n");}String modelHtml = sBuilder.toString();inputStream.close();reader.close();String contentNew = modelHtml.replace("<--@#$%discoverContent@#$%-->", content);if (night) {contentNew = contentNew.replace("<--@#$%colorfontsize2@#$%-->","color:#8f8f8f ;");} else {contentNew = contentNew.replace("<--@#$%colorfontsize2@#$%-->","color:#333333 ;");}if (flag) {contentNew = contentNew.replace("<--@#$%colorbackground@#$%-->", "background:#B4CDE6");} else {contentNew = contentNew.replace("<--@#$%colorbackground@#$%-->", "background:#F9BADA");}return contentNew;} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}

通过这段代码,就可以设置更改字体颜色,和背景色。另再附上一个简单的模板,仅供参考。

<html> <head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"><meta name="viewport"content="width = device-width, initial-scale = 1, minimum-scale = 1, maximum-scale = 1" /><title></title><link href="newscont.css" type="text/css" rel="stylesheet"></link></head> <body style="" data-webview-width="{{webview_width}}"data-webview-height="{{webview_height}} "><div id="content" class="main fontSize1"><p class="title" align="center" id="title"style="font-family: 'Microsoft YaHei';"><!-- 标题 --></p><div><span class="src" id="source" style="font-family: 'Microsoft YaHei';"><!-- 来源 --> </span>  </div><div id="discoverContent"style="margin-top: 10px; <--@#$%colorbackground@#$%-->;border-top: 0px solid #cbcbcb; font-family: 'Microsoft YaHei'; <--@#$%colorfontsize2@#$%-->; width: 100%; height: auto"><!-- 正文 --><--@#$%discoverContent@#$%-->  </div></div></body> <script language="javascript" src="jquery.js" charset="utf-8"></script><script src="jquery.lazyload.js" type="text/javascript" charset="utf-8"></script><script src="newscont.js" type="text/javascript" charset="utf-8"></script><script type="text/javascript" charset="utf-8">function addlist(listStr) {var elem = document.getElementById("recommand-list");elem.innerHTML = listStr;}$(document).ready(function() { tna.adjustImageSize(); $("img").lazyload({effect : "fadeIn"});}); </script></html>


转载请注明出处http://blog.csdn.net/lxm20819/article/details/51121461

0 0
原创粉丝点击