recent projects have met with a very tricky problem :
The data that the customer gave me is limited, so when I return to the content of a detailed page, he can just give me an HTML fragment, which includes
Text, pictures, and attachments. Let's say the love of the Web Template specification is better, but he gives me a lot of uncertainty in the data:
For example, there may be no pictures, pictures and text interspersed together, the most important is the HTML note his nesting level and the number of tags are indeterminate.
Assuming that I extract the content using parsing HTML, I'm expected to fall into the pit ....
However, in the actual situation, the intention of the server will first remove the tag attributes of the customer code, only bones, but the results are still unsatisfactory, due to the deletion of all the original tag attributes, the display will still have problems ....
so , I looked at the NetEase news and other feelings are used WebView to show, the key is how to encapsulate and processing good data.
learn to walk, or start with imitation. This is a reference to the blog, experience of Daniel, once again thanked:
http://blog.csdn.net/zi413293813/article/details/18144055
http://blog.csdn.net/kavensu/article/details/7931480
http://blog.csdn.net/wangtingshuai/article/details/8635787
http://blog.csdn.net/chenshijun0101/article/details/7045394
my needs: Download images, download attachments,
Use the idea: the content is displayed in HTML, and the interaction between Java and JS is implemented in response to the action of the user clicking on the picture.
Here I wrote a demo, according to the other people's sample simple encapsulation, of course, here is only to provide a way of thinking, detailed how to encapsulate how to achieve better or more detailed analysis of the problem.
Don't forget: Add write file permissions and network permissions
Demo Use test page: http://www.cnbeta.com/articles/292267.htm
Here, because of his content too much, so I went directly to the main content part, that is, I have mixed words and pictures of the part.
Interface: Mainly used for callbacks, of course, in order to expand, but also to add many other methods.
Package com.example.androidwebviewdemo;/** * <p> * </p> * PM 8:04:06 * * @auther XIANGXM */public interface Ionwebviewcallback {/** * <p> * page Loading progress * </p> * * @param progress * void */void onprogresschanged (int progress);}
To set the related properties of the WebView control:
private void Initview () {ProgressBar = (ProgressBar) Findviewbyid (R.id.progressbar);p rogressbar.setvisibility ( view.invisible); Mwebview = (WebView) Findviewbyid (R.ID.WEBVIEW_UI); WebSettings settings = Mwebview.getsettings ();//Set WebView related properties settings.setjavascriptenabled (true);// Agree to run JS code settings.setblocknetworkimage (TRUE); Settings.setsupportzoom (false);// Scaling Settings.setbuiltinzoomcontrols (FALSE) is not supported;//built-in scaling settings.setpluginsenabled (true); Settings.setdefaulttextencodingname ("UTF-8");//Set the default encoding Mwebview.getsettings (). Setlayoutalgorithm ( Layoutalgorithm.single_column);//Forbidden because the content is too wide, resulting in a horizontal screen scrolling. Mwebview.addjavascriptinterface (New Javascriptinterface (), htmlparser.js2javainterfacename); Htmlparser htmlparser = new Htmlparser (Mwebview, "http://www.cnbeta.com/articles/292267.htm", this, this); Htmlparser.execute ();}
Htmlparser: According to other people's code changes, I mainly put the other operations are put in. Feel that this will involve too much, not good expansion, but here is only a demo.
Directly on the code: Htmlparser
Package Com.example.androidwebviewdemo;import Java.io.file;import Java.io.ioexception;import Java.net.malformedurlexception;import Java.net.url;import Java.util.arraylist;import Java.util.List;import Org.jsoup.jsoup;import Org.jsoup.nodes.document;import Org.jsoup.nodes.element;import org.jsoup.select.Elements; Import Android.content.context;import android.graphics.bitmap;import android.os.asynctask;import android.util.Log; Import Android.view.view;import Android.webkit.webchromeclient;import Android.webkit.webview;import android.webkit.webviewclient;/** * <p> * HTML processing related classes: Add the onclick attribute to the image. , filter a tag, add attributes, and so on. , * </p> * PM 6:40:37 * * @auther XIANGXM */public class Htmlparser extends Asynctask<void, Void, string> {Pub Lic static string js2javainterfacename = "Jsusejava";p rivate WebView mwebview;/** web address **/private string htmlurl = "";p Riv Ate Context mcontext;/** stores the img tag image address. **/private list<string> imageurllist = new arraylist<string> ();p ublic list<string> getImAgerurllist () {return imageurllist;} Public Htmlparser (WebView wevview, String url, Context context,ionwebviewcallback onwebviewcallback) {This.mwebview = Wevview;htmlurl = Url;mcontext = Context;this.onwebviewcallback = Onwebviewcallback;configwebview ();} /** * <p> * configuration information for WebView * </p> * void */private void Configwebview () {//mwebview.setwebviewclient (new MyWeb Client ()); Mwebview.setwebchromeclient (new Mywebchrome ());} Class Mywebclient extends Webviewclient {@Overridepublic void onpagestarted (WebView view, String URL, Bitmap favicon) {sup er.onpagestarted (view, URL, favicon);} @Overridepublic void onpagefinished (WebView view, String URL) {super.onpagefinished (view, URL); Mwebview.getsettings () . Setblocknetworkimage (false);//Close Picture blocked//page loading finished, replace the picture display, asynchronous replacement picture display. Downloadwebimgtask downloadtask = new Downloadwebimgtask (Mwebview); list<string> urlstrs = imageurllist; String urlstrarray[] = new String[urlstrs.size () + 1];urlstrs.toarray (urlstrarray);d Ownloadtask.execute (URLSTRARRay); if (null! = Onwebviewcallback) {onwebviewcallback.onprogresschanged (view.invisible);}} @Overridepublic Boolean shouldoverrideurlloading (WebView view, String URL) {//When the connection is clicked, you want to overwrite instead of opening a new form//View.loadurl ( URL); return true;}} Class Mywebchrome extends Webchromeclient {@Overridepublic void onprogresschanged (WebView view, int newprogress) { Super.onprogresschanged (view, newprogress);//load shows the running progress can be added here if (null! = Onwebviewcallback) {//load shows the time of the running progress// Onwebviewcallback.onprogresschanged (newprogress);}}} Private Ionwebviewcallback onwebviewcallback;public void Setonwebviewcallback (Ionwebviewcallback onWebViewCallBack) {this.onwebviewcallback = Onwebviewcallback;} /** * <p> * Inject JS code, add onclick event * </p> * * @param doc * void */public void handleimageclickevent (Do Cument doc) {Elements es = Doc.getelementsbytag ("img"); for (Element e:es) {String Imgurl = e.attr ("src"); imageurllist.ad D (Imgurl); String imgname; File File = new file (imgurl); imgname = File.getname (); if (imgname. EndsWith (". gif")) {E.remove ();} else {String FilePath = "file:///mnt/sdcard/test/" + imgname;e.attr ("src", "file:/// Android_asset/ic_launcher.png "); E.attr (" Src_link ", FilePath); E.attr (" Ori_link ", Imgurl); String str = "window." + Js2javainterfacename + ". Setimgsrc ('" + FilePath + "')"; E.attr ("onclick", str);}} /** * <p> * Interaction with Java will be a hyperlink tag, click to provide download * </p> * * @param doc * void */private void Handlehyperlinks (D Ocument doc) {Elements hrefs = Doc.getelementsbytag ("a"); for (Element href:hrefs) {String str = "window." + Js2javainter FaceName + ". Onclick_tag_a ('" + href.attr ("href") + "')"; Href.attr ("OnClick", str);}} @Overrideprotected String doinbackground (Void ... params) {if (null! = Onwebviewcallback) { Onwebviewcallback.onprogresschanged (view.visible);} Document doc = Null;imageurllist.clear (); try {doc = Jsoup.parse (new URL (Htmlurl), 15000);} catch (Malformedurlexception E 1) {e1.printstacktrace ();} catch (IOException E1) {e1.printstacktrace ();} if (doc = = null) return nulL Elements es = doc.select ("script"), if (es! = null) {Es.remove ();} Document docnew = Jsoup.parse (Doc.getelementsbyclass ("Article_content"). html ()); Handleimageclickevent (DOCNEW); Handlehyperlinks (docnew); LOG.I ("-------->html content", docnew.tostring ()); return docnew.tostring ();} @Overrideprotected void OnPostExecute (String result) {Super.onpostexecute (result); Mwebview.loaddatawithbaseurl ( NULL, result, "text/html", "Utf-8", null);//This display can effectively place the Chinese garbled super.onpostexecute (result);}}
When you click on a picture: Usually it jumps to the browser's new page overlay. The realization of the demand here is, click on the image does not jump, directly webviewclient shouldoverrideurlloading return True, the event consumption is OK.
@Overridepublic Boolean shouldoverrideurlloading (WebView view, String URL) {//When the connection is clicked, you want to overwrite instead of opening a new form//View.loadurl ( URL); return true;}
Perform:
The demo shows something slow.
Source: http://download.csdn.net/detail/xxm282828/7362539
Related uses of WebView in Android