Android WebView 圖片超出寬度自適應,點選檢視大圖
阿新 • • 發佈:2018-12-09
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處理事件
public static class JavaScriptInterface { private Context context; public JavaScriptInterface(Context context) { this.context = context; } //點選圖片回撥方法 //必須添加註解,否則無法響應 @JavascriptInterface public 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() { @Override public 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物件
webView.addJavascriptInterface(new ImgTool.JavaScriptInterface(ShowTextActivity.this), "imagelistner");
webView.loadUrl(url);