webview是android比较重要和常用的控件,网络上很多相关内容,在此介绍下WebViewClient比较少见的操作:
我们获取WebView里面链接别的网页的url地址
private class MyWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return true; //返回true才能在当前WebView显示url链接内容,否则会打开其它浏览器 } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); initCollectionImageBtn(url); //1、 view.getOriginalUrl()初始加载为空null,此后该值==view.getUrl() != url // 2、并且url等于onPageFinished的值 imgButtonFresh.setImageDrawable(getResources().getDrawable( R.drawable.selector_nav_to_refresh_stop)); } @Override public void onPageFinished(WebView view, String url) { // view.getOriginalUrl() == view.getUrl() == url if (isCollection) { changeCollectionImgBg(COLLECTION_SATE_AFTER); } else { changeCollectionImgBg(COLLECTION_SATE_BEFORE); } imgButtonFresh.setImageDrawable(getResources().getDrawable( R.drawable.selector_nav_to_refresh)); view.loadUrl("javascript:" + handleWebViewHeader(url)); super.onPageFinished(view, url); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); } }
以上代码是项目的一个代码片段,url的值参考上面代码,其中onPageFinished()函数中view.loadUrl("javascript:"+handleWebViewHeader(url))是加载经过处理后的HTML页面,该处是去除header内容:
"document.body.removeChild(document.getElementsByTagName(\"header\")[0])";
或者 "document.body.removeChild(document.getElementsByClassName(\"header\")[0])";