webView = (WebView) findViewById(R.id.info_detail_webview); WebSettings webSettings = webView.getSettings(); webSettings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); webSettings.setJavaScriptEnabled(true); // 添加js交互接口类,并起别名 imagelistner LogUtil.verbose("json", "url= " + newsList.Url); webView.loadUrl(newsList.Url); // 添加js交互接口类,并起别名 imagelistner webView.addJavascriptInterface(new JavascriptInterface(this), "imagelistner"); webView.setWebViewClient(new MyWebViewClient());
监听接口:
// js通信接口 public class JavascriptInterface { private Context context; public JavascriptInterface(Context context) { this.context = context; } public void openImage(String img) { LogUtil.verbose("json", "img= " + img); Intent intent = new Intent(); intent.putExtra("image", img); intent.setClass(context, ShowWebImageActivity.class); context.startActivity(intent); } } // 注入js函数监听 private void addImageClickListner() { // 这段js函数的功能就是,遍历所有的img几点,并添加onclick函数,在还是执行的时候调用本地接口传递url过去 webView.loadUrl("javascript:(function(){" + "var objs = document.getElementsByTagName("img"); " + "for(var i=0;i<objs.length;i++) " + "{" + " objs[i].onclick=function() " + " { " + " window.imagelistner.openImage(this.src); " + " } " + "}" + "})()"); }
重写WebViewClient:
/** 监听WebView加载URL进度 **/ class MyWebViewClient extends WebViewClient { @Override public void onPageFinished(WebView view, String url) { // TODO Auto-generated method stub view.getSettings().setJavaScriptEnabled(true); // html加载完成之后,添加监听图片的点击js函数 addImageClickListner(); hideTopProgressBar(); super.onPageFinished(view, url); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // TODO Auto-generated method stub return super.shouldOverrideUrlLoading(view, url); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { // TODO Auto-generated method stub view.getSettings().setJavaScriptEnabled(true); super.onPageStarted(view, url, favicon); } }
拦截系统Back事件:
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub // 拦截系统的返回事件 调用webview的 if(webView.canGoBack() && keyCode == KeyEvent.KEYCODE_BACK){ webView.goBack(); return true; } return super.onKeyDown(keyCode, event); }