webView 配置
WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptCanOpenWindowsAutomatically(true);webSettings.setDomStorageEnabled(true);webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//自适应屏幕 ☆☆webSettings.setDisplayZoomControls(false);webSettings.setJavaScriptEnabled(true); // 设置支持javascript脚本 ☆☆webSettings.setAllowFileAccess(true); // 允许访问文件webSettings.setBuiltInZoomControls(true); // 设置显示缩放按钮webSettings.setSupportZoom(true); // 支持缩放webSettings.setLoadWithOverviewMode(true);webSettings.setUseWideViewPort(true);
Android处理事件(ImgTool.java)
public static class JavaScriptInterface {private Context context;public JavaScriptInterface(Context context) {this.context = context;}//点击图片回调方法//必须添加注解,否则无法响应@JavascriptInterfacepublic void openImage(String imgsrc) { Bitmap bitmap = null;try{bitmap = BitmapFactory.decodeStream(new URL(imgsrc).openStream());} catch (IOException e){e.printStackTrace();}Drawable drawable;if (bitmap != null){drawable = new BitmapDrawable(context.getResources(), bitmap);//弹出个全屏窗口打开图片对象 自己写就行了//ImgTool.ViewImg((Activity) context,drawable);}}}
重写 onPageFinished 注入js
webView.setWebViewClient(new WebViewClient(){@Overridepublic void onPageFinished(WebView view, String url){super.onPageFinished(view, url);/*** 对图片进行重置大小,宽度就是手机屏幕宽度,高度根据宽度比便自动缩放**/webView.loadUrl("javascript:(function(){"+ "var objs = document.getElementsByTagName('img'); "+ "for(var i=0;i<objs.length;i++) "+ "{"+ "var img = objs[i]; "+ " img.style.maxWidth = '100%'; img.style.height = 'auto'; "+ "}"+ "})()");// html加载完成之后,添加监听图片的点击js函数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); "+ " } "+ "}"+ "})()");} });
//AndroidtoJS类对象映射到js的openImage对象 YourActivity 也就是当前的activitywebView.addJavascriptInterface(new ImgTool.JavaScriptInterface(YourActivity.this), "imagelistner");webView.loadUrl(url);