Recently I encountered a very difficult problem in my project:
The data that the customer gives me is limited. Therefore, when returning a specific page content, he can only give me an html clip that contains
Text, images, and attachments. There are many uncertainties in the data that he gives me:
For example, there may be no images, and images and text are interspersed together. The most important thing is that the nested layers of html tabs and the number of tags are uncertain.
If I parse html to extract the content, it is estimated that it will fall into the trap .......
However, in actual situations, the server is planning to delete the tag attribute of the Customer Code with only bones left, but the results are still unsatisfactory, because after deleting all the original tag attributes, the display still has problems ...........
Therefore, I have read Netease news and other ideas, all of which are displayed using webview. The key is how to encapsulate and process data.
Learning to walk begins with imitating. I have learned from the blogs and experiences of the experts, and I would like to thank you again:
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 requirements: Download images, download attachments,
Idea: display the content in html and implement interaction between java and js to respond to users' clicks on images.
Here I wrote a demo, which is simply encapsulated according to the above examples. Of course, here is just a way of thinking, how to encapsulate and implement it is better to analyze specific issues.
Don't forget:Add write and network Permissions
Demo use test page: http://www.cnbeta.com/articles/292267.htm
Here, because he has too much content, I directly go to the main content section, that is, the section where I mix my text and images.
Interface: it is mainly used for callback. Of course, you can add more methods for expansion.
Package com. example. androidwebviewdemo ;/****
* 8:04:06 PM ** @ auther xiangxm */public interface IOnWebViewCallBack {/**** Page loading progress *
** @ Param progress * void */void onProgressChanged (int progress );}
Set the attributes of the webview control:
Private void initView () {progressbar = (ProgressBar) findViewById (R. id. progressbar); progressbar. setVisibility (View. INVISIBLE); mWebView = (WebView) findViewById (R. id. webview_ui); WebSettings settings = mWebView. getSettings (); // set the attributes of webview. setJavaScriptEnabled (true); // allows the execution of js Code settings. setBlockNetworkImage (true); settings. setsuppzoom zoom (false); // scaling settings is not supported. setBuiltInZoomControls (false ); // Built-in zoom settings. setPluginsEnabled (true); settings. setDefaultTextEncodingName ("UTF-8"); // sets the default encoding mWebView. getSettings (). setLayoutAlgorithm (LayoutAlgorithm. SINGLE_COLUMN); // prohibit horizontal scrolling because the content is too wide. MWebView. addJavascriptInterface (new JavaScriptInterface (), HtmlParser. Js2JavaInterfaceName); HtmlParser htmlParser = new HtmlParser (mWebView, "http://www.cnbeta.com/articles/292267.htm", this, this);htmlParser.exe cute ();}
HtmlParser: according to the code changed by others, I mainly put other operations into it. I feel that this will involve too much and it is difficult to expand, but it is just a demo.
Directly run 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 ;/**** Related html processing class: add the onClick attribute to the image ., Filter a tags and add attributes. ,*
* 6:40:37 PM ** @ auther xiangxm */public class HtmlParser extends AsyncTask
{Public static String Js2JavaInterfaceName = "JsUseJava"; private WebView mWebView;/** webpage address **/private String htmlUrl = ""; private Context mContext; /** store the img Tag image address. **/Private List
ImageUrlList = new ArrayList
(); Public List
GetImagerUrlList () {return imageUrlList;} public HtmlParser (WebView wevView, String url, Context context, IOnWebViewCallBack onWebViewCallBack) {this. mWebView = wevView; htmlUrl = url; mContext = context; this. onWebViewCallBack = onWebViewCallBack; configWebView ();}/***
* Configure WebView information *
* Void */private void configWebView () {// mWebView. setWebViewClient (new MyWebClient (); mWebView. setWebChromeClient (new MyWebChrome ();} class MyWebClient extends WebViewClient {@ Overridepublic void onPageStarted (WebView view, String url, Bitmap favicon) {super. onPageStarted (view, url, favicon) ;}@ Overridepublic void onPageFinished (WebView view, String url) {super. onPageFinished (view, url); mWebView. get Settings (). setBlockNetworkImage (false); // disable Image Blocking // After the page is loaded, change the image display and asynchronously change the image display. DownloadWebImgTask downloadTask = new DownloadWebImgTask (mWebView); List
UrlStrs = imageUrlList; String urlStrArray [] = new String [urlStrs. size () + 1100000000urlstrs.toarray(urlstrarray##downloadtask.exe cute (urlStrArray); if (null! = OnWebViewCallBack) {onWebViewCallBack. onProgressChanged (View. INVISIBLE) ;}@ Overridepublic boolean shouldOverrideUrlLoading (WebView view, String url) {// You Want to overwrite the connection when it is clicked, instead of opening a new window. // view. loadUrl (url); return true;} class MyWebChrome extends WebChromeClient {@ Overridepublic void onProgressChanged (WebView view, int newProgress) {super. onProgressChanged (view, newProgress); // you can add if (null! = OnWebViewCallBack) {// when loading the display progress // onWebViewCallBack. onProgressChanged (newProgress) ;}} private IOnWebViewCallBack onWebViewCallBack; public void setOnWebViewCallBack (IOnWebViewCallBack onWebViewCallBack) {this. onWebViewCallBack = onWebViewCallBack ;}/***
* Inject js Code and add an Onclick event *
** @ Param doc * void */public void handleImageClickEvent (Document doc) {Elements es = doc. getElementsByTag ("img"); for (Element e: es) {String imgUrl = e. attr ("src"); imageUrlList. add (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 );}}}/***
* For interaction with java, click the "ahyperlink" tab to download the link *
** @ Param doc * void */private void handleHyperlinks (Document doc) {Elements hrefs = doc. getElementsByTag ("a"); for (Element href: hrefs) {String str = "window. "+ Js2JavaInterfaceName + ". 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 e1) {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 Chinese garbled characters in super. onPostExecute (result );}}
After you click an image, the new page of the browser overwrites the image. To achieve this, click the image and do not jump. directly return true to shouldOverrideUrlLoading of WebViewClient. If the event is consumed, OK is returned.
@ Overridepublic boolean shouldOverrideUrlLoading (WebView view, String url) {// You Want to overwrite the connection when it is clicked, instead of opening a new window. // view. loadUrl (url); return true ;}
Run:
The demo displays the content slowly.
Source code: http://download.csdn.net/detail/xxm282828/7362539