Android webview js交互, 响应webview中的图片点击事件《2》

思路:
①自定义interface

class MyJavaScriptInterface {
        public MyJavaScriptInterface() {
        }
        @JavascriptInterface
        public void openImage(String img) {
            System.out.println(img);
//          ToastUtils.longToast("openPhotoOnAndroid");
            Intent intent = new Intent(BrowserActivity.this, ViewPagerActivity.class);
            ArrayList mImgUrlList = new ArrayList<>();
            mImgUrlList.add(img);
            intent.putStringArrayListExtra("IMG_LIST", mImgUrlList);
            startActivity(intent);
        }
        @JavascriptInterface
        public void openPhotoOnAndroid(final String index, final String jsonStr) {
            runOnUiThread(new Runnable() {
                public void run() {
//                            int j = i;
//                            j++;
//                            //Log.v("TAG", "index:"+"jsonStr:");
//                    //Log.v("TAG", "index:"+index+"jsonStr:"+ jsonStr);
//                    shortToast("openPhotoOnAndroid");
                    ArrayList imgList = new Gson().fromJson(jsonStr, new TypeToken>() {
                    }.getType());
                    Intent intent = new Intent(BrowserActivity.this, ViewPagerActivity.class);
                    intent.putExtra("START_INDEX", Integer.valueOf(index));
                    ArrayList mImgUrlList = new ArrayList<>();
                    for (ImageBean imageBean : imgList) {
                        mImgUrlList.add(imageBean.getSrc());
                    }
                    intent.putStringArrayListExtra("IMG_LIST", mImgUrlList);
                    startActivity(intent);
//                            Toast.makeText(EvaluateDetailActivity.this, "测试调用java" + String.valueOf(index), Toast.LENGTH_LONG).show();
                }
            });
        }
        @JavascriptInterface
        public void resize(final float height) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //Toast.makeText(getActivity(), height + "", Toast.LENGTH_LONG).show();
                    //此处的 layoutParmas 需要根据父控件类型进行区分,这里为了简单就不这么做了
                    mWebView.setLayoutParams(new RelativeLayout.LayoutParams(getResources().getDisplayMetrics().widthPixels, (int) (height * getResources().getDisplayMetrics().density)));
                }
            });
        }
    }

②通过webview交互接口,为html页面提供js函数

webVieww.addJavascriptInterface(new MyJavaScriptInterface(this), "imagelistner");

③为img标签注册listener

// 注入js函数监听
    private void addImageClickListner() {
        // 这段js函数的功能就是,遍历所有的img几点,并添加onclick函数,函数的功能是在图片点击的时候调用本地java接口并传递url过去
        webView.loadUrl("javascript:(function(){" +
        "var objs = document.getElementsByTagName(\"img\"); " + 
                "for(var i=0;i

你可能感兴趣的:(Android webview js交互, 响应webview中的图片点击事件《2》)