`
liuxin-smallmouse
  • 浏览: 18116 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

【OSC手机App技术解析】- 在WebView中组装HTML

阅读更多

上一篇我们介绍了 OSChina.NET 手机客户端上应用内Web链接的处理 ,本篇将介绍如何在 WebView 控件中组装 HTML 显示。


先上张效果图:

由于在 WebView 上显示HTML,不可能只显示纯文本,而没有一点样式,这会显得很难看,下面代码就是定义了一个全局的样式:

public final static String WEB_STYLE = "<style>* {font-size:16px;line-height:20px;} p {color:#333;} a {color:#3E62A6;} img {max-width:310px;} " +
	"pre {font-size:9pt;line-height:12pt;font-family:Courier New,Arial;border:1px solid #ddd;border-left:5px solid #6CE26C;background:#f6f6f6;padding:5px;}</style>";

 上面全局样式:“*”定义了字体大小以及行高;“p”标签内的字体颜色;“a”标签内的字体颜色;“img”标签的图片最大宽度;“pre”为代码样式;

资讯内容是由服务返回的一串带HTML标签的字符串:

String body = newsDetail.getBody();

 相关资讯则是由服务返回的数据组装的:

String strRelative = "";
for(Relative relative : newsDetail.getRelatives()){
&nbsp;&nbsp;&nbsp; strRelative += String.format("<a href='%s' style='text-decoration:none'>%s</a><p/>", relative.url, relative.title);
}

 图片处理
WebView上显示图片,不能直接显示大图,这会影响页面的美观以及用户体验,因此要过滤掉原始图片的高宽属性,使用全局的图片样式。同时客户端可以根据用户设置,是否加载图片显示,以达到节省流量的目的。

if(isLoadImage){
&nbsp;&nbsp;&nbsp; //过滤掉 img标签的width,height属性
&nbsp;&nbsp;&nbsp; body = body.replaceAll("(<img[^>]*?)\\s+width\\s*=\\s*\\S+","$1");
&nbsp;&nbsp;&nbsp; body = body.replaceAll("(<img[^>]*?)\\s+height\\s*=\\s*\\S+","$1");
}else{
&nbsp;&nbsp;&nbsp; //过滤掉 img标签
&nbsp;&nbsp;&nbsp; body = body.replaceAll("<\\s*img\\s+([^>]*)\\s*>","");
}

 WebView展示HTML

 

mWebView.loadDataWithBaseURL(null, body, "text/html", "utf-8",null);

 完整代码:

//资讯内容
String body = newsDetail.getBody();					

if(!body.trim().startsWith("<style>")){
	body = WEB_STYLE + body;
}

//相关资讯
if(newsDetail.getRelatives().size() > 0)
{
	String strRelative = "";
	for(Relative relative : newsDetail.getRelatives()){
		strRelative += String.format("<a href='%s' style='text-decoration:none'>%s</a><p/>", relative.url, relative.title);
	}
	body += String.format("<p/><hr/><b>相关资讯</b><div><p/>%s</div>", strRelative);
}

//读取用户设置:是否加载文章图片
if(isLoadImage){
	//过滤掉 img标签的width,height属性
	body = body.replaceAll("(<img[^>]*?)\\s+width\\s*=\\s*\\S+","$1");
	body = body.replaceAll("(<img[^>]*?)\\s+height\\s*=\\s*\\S+","$1");
}else{
	//过滤掉 img标签
	body = body.replaceAll("<\\s*img\\s+([^>]*)\\s*>","");
}			

mWebView.loadDataWithBaseURL(null, body, "text/html", "utf-8",null);
 

在WebView上的站内链接的点击处理,请查看上篇应用内Web链接的处理

如果大家有什么疑问的话,欢迎在下面回帖一起探讨。

PS:

OSC Android客户端下载地址: http://www.oschina.net/uploads/osc.apk

OSC iPhone客户端下载地址: http://www.oschina.net/uploads/osc.ipa
OSC Windows Phone客户端下载地址: http://www.oschina.net/uploads/osc.xap

 

转载:http://www.oschina.net/question/157182_59135

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics