上一篇我們介紹了 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()){ strRelative += String.format("<a href='%s' style='text-decoration:none'>%s</a><p/>", relative.url, relative.title); }
圖片處理
WebView上顯示圖片,不能直接顯示大圖,這會影響頁面的美觀以及用戶體驗,因此要過濾掉原始圖片的高寬屬性,使用全局的圖片樣式。同時客戶端可以根據用戶設置,是否加載圖片顯示,以達到節省流量的目的。
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*>",""); }
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