版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/admans/article/details/82624480
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);