在一次开发中,产品突然说了一句能不能实现点击咋们的网页中的图片,能够单独显示,当时也是一脸懵逼,之后想了想,其实也就是响应webview中的图片事件而已,实现起来也不是很难。
实现思路:
-
使用WebView的js注入,为HTML加入js函数监听
-
在Android中添加当触发HTMl中js方法的接口
具体步骤如下:
1. mWebView = (WebView) findViewById(R.id.wv_test);
//获得webview的设置,并设置webview支持js
mWebView.getSettings().setJavaScriptEnabled(true);
2.// 添加js交互接口类,并起别名 imagelistner
mWebView.addJavascriptInterface(new SupportJavascriptInterface(this),"imagelistner");
3.// html加载完成之后,添加监听图片的点击js函数
mWebView.setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView view, String url) {
addWebImageClickListner(view);
}
// 注入js函数监听
protected void addWebImageClickListner(WebView webView) {
// 这段js函数的功能就是,遍历所有的img节点,并添加onclick函数,
// 函数的功能是在图片点击的时候调用本地java接口并传递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); " +
" } " +
"}" +
"})()");
}
}
/**
* js接口
*/
public class SupportJavascriptInterface {
private Context context;
public SupportJavascriptInterface(Context context) {
this.context = context;
}
@JavascriptInterface
public void openImage(final String img) {
runOnUiThread(new Runnable() {
@Override
public void run() {
gotoImageBrowse(img);
}
});
}
}
public void gotoImageBrowse(String imgUrl) {
if (TextUtils.isEmpty(imgUrl))
return;
/*Bundle bundle = new Bundle();
bundle.putString("arg_key_image_browse_url", imgUrl);
startActivity(ImageBrowseActivity.class, bundle);*/
Toast.makeText(BaseWebActivity.this,"图片地址:"+imgUrl,Toast.LENGTH_SHORT).show();
}