今天介绍一下怎么查看WebView里面的图片,首先要设置WebView能够支持JavaScript,然后实现JavaScript的监听接口:
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.addJavascriptInterface(
newJavascriptInterface(this.getActivity()), "ImageListener");
下面是JavaScript接口的代码:
public class JavascriptInterface {
private Context context;
publicJavascriptInterface(Context context) {
this.context= context;
}
public voidClickImage(String imageUrl) {
Intent intent= new Intent();
intent.putExtra("ImageUrl",imageUrl);
LogHelper.i(imageUrl);
intent.setClass(context,WebViewImageActivity.class);
context.startActivity(intent);
}
}
在WebView的图片上添加事件:
private void InjectWebViewClickListener() {
StringBuilder str = newStringBuilder();
str.append("javascript:(function(){");
str.append("$('img').each(function(idx,obj){");
str.append("$(obj).click(function(){");
str.append("windows.imageListener.ClickImage($(obj).attr('src'));");
str.append("});});})()");
mWebView.loadUrl(str.toString());
}
最后在WebView的WebViewClient里调用这个事件:
mWebView.setWebViewClient(new WebViewClient() {
@Override
public voidonReceivedError(WebView view, int errorCode,
Stringdescription, String failingUrl) {
super.onReceivedError(view,errorCode, description, failingUrl);
}
@Override
public voidonPageFinished(WebView view, String url) {
super.onPageFinished(view,url);
//html加载完成之后,添加监听图片的点击js函数
InjectWebViewClickListener();
}
});