setWebViewClient(new WebViewClient() {
// 页面加载完成调用
@Override
public void onPageFinished(WebView view, String url)
super.onPageFinished(view, url);
addImageClickListner();
}
}
private void addImageClickListner() {
// 这段js函数的功能就是,遍历所有的img几点,并添加onclick函数,函数的功能是在图片点击的时候调用本地java接口并传递url过去
loadUrl("javascript:(function(){" +
"var objs = document.getElementsByTagName(\"img\");" +
"var imgScrs =\"\";" +
"for(var i=0;i<objs.length;i++) " +
"{" +
"imgScrs+=objs[i].src;" +
"if(i+1<imgs.length)" +
"imgScrs+=\"*\";"
+ " objs[i].onclick=function() " +
" { "
+ " window.imagelistner.openImage(this.src,imgScrs); " +
" } " +
"}" +
"})()");
}
addJavascriptInterface(JavascriptInterface(context), "imagelistner");
// js通信接口
private Object JavascriptInterface(final Context context){
Object insertObject=new Object(){
@JavascriptInterface
public void openImage(String img,String imgList) {
int position=0;
String[] imgLists=imgList.split("\\*");
for(int i=0;i<imgLists.length;i++)
if(img.equals(imgLists[i]))
position=i;
Log.v("imgLists",imgLists);
Log.v("position",position);
}
};
return insertObject;
}
// 页面加载完成调用
@Override
public void onPageFinished(WebView view, String url)
super.onPageFinished(view, url);
addImageClickListner();
}
}
private void addImageClickListner() {
// 这段js函数的功能就是,遍历所有的img几点,并添加onclick函数,函数的功能是在图片点击的时候调用本地java接口并传递url过去
loadUrl("javascript:(function(){" +
"var objs = document.getElementsByTagName(\"img\");" +
"var imgScrs =\"\";" +
"for(var i=0;i<objs.length;i++) " +
"{" +
"imgScrs+=objs[i].src;" +
"if(i+1<imgs.length)" +
"imgScrs+=\"*\";"
+ " objs[i].onclick=function() " +
" { "
+ " window.imagelistner.openImage(this.src,imgScrs); " +
" } " +
"}" +
"})()");
}
addJavascriptInterface(JavascriptInterface(context), "imagelistner");
// js通信接口
private Object JavascriptInterface(final Context context){
Object insertObject=new Object(){
@JavascriptInterface
public void openImage(String img,String imgList) {
int position=0;
String[] imgLists=imgList.split("\\*");
for(int i=0;i<imgLists.length;i++)
if(img.equals(imgLists[i]))
position=i;
Log.v("imgLists",imgLists);
Log.v("position",position);
}
};
return insertObject;
}