WebView与Javascript交互

来源:互联网 发布:p2p网络正在连接 编辑:程序博客网 时间:2024/05/21 00:18

Android中可以使用WebView加载网页,同时Android端的java代码可以与网页上的javascript代码之间相互调用。

效果图webview的图片中点击,出发js方法,得到图片数据

  1. 画布局就省略了啊
  2. `@SuppressLint({“SetJavaScriptEnabled”, “AddJavascriptInterface”})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    webView=(WebView)findViewById(R.id.webView);
    webView.setVerticalScrollbarOverlay(true);
    //设置WebView支持JavaScript
    webView.getSettings().setJavaScriptEnabled(true);
    String url = “http://undefined.cunite.cn/test/gallery.html“;
    String url2 = “http://undefined.cunite.cn/a.html“;
    webView.loadUrl(url);

    //在js中调用本地java方法webView.addJavascriptInterface(new JsInterface(this), "AndroidWebView");//添加客户端支持webView.setWebChromeClient(new WebChromeClient());

    }

     private class JsInterface {        private Context mContext;        public JsInterface(Context context) {            this.mContext = context;        }        //在js中调用window.AndroidWebView.gallery(json),便会触发此方法。        @JavascriptInterface        public void gallery(String json) {          //  Toast.makeText(mContext, gallery_json, Toast.LENGTH_SHORT).show();            Log.i("gallery",json);        }    }

这样就可以在js中调用java 的同名方法了

在js中这个方法是这样子的:
window.AndroidWebView.gallery(json);

这时候当我们在手机中点击webview上边的图片,就会调用js中的gallery(json) 这个方法。
这时候就会有如下打印
{
“current”: 2,
“total”: 12,
“list”: [
“Source_new/pic/1.jpg”,
“Source_new/pic/2.jpg”,
“Source_new/pic/3.jpg”,
“Source_new/pic/4.jpg”,
“Source_new/pic/5.jpg”,
“Source_new/pic/6.jpg”,
“Source_new/pic/7.jpg”,
“Source_new/pic/8.jpg”,
“Source_new/pic/9.jpg”,
“Source_new/pic/10.jpg”,
“Source_new/pic/11.jpg”,
“Source_new/pic/12.jpg”
]
}
我们就可以取其中的数据了

特此鸣谢:http://itfish.net/article/25514.html

0 0
原创粉丝点击