内容简介:java与Js交互
现在越来越多的app使用原生和H5混合开发了,可以减少开发周期。
一、android调用JS代码。
mWeb.loadUrl("javascript:upload_img('" + mPicUrl + "')")
这是直接调用js的upload_img的方法。
举个例子:
js的代码如下:
function callJS(){ alert("Android调用了JS的callJS方法"); }
Android调用这个代码:
mWeb.loadUrl("javascript:callJS()");
二、js调用Android代码:
首先webView需要设置:
WebSettings webSettings = mWebView.getSettings(); // 设置可以与Js交互的权限 webSettings.setJavaScriptEnabled(true); //实例化Javascript对象 final JavaScriptInterface myJavaScriptInterface = new JavaScriptInterface(this); // 通过addJavascriptInterface()将 Java 对象映射到JS对象 //参数1:Javascript对象名 //参数2:Java对象名 mWebView.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
JavaScriptInterface类代码:
private class JavaScriptInterface { Context mContext; JavaScriptInterface(Context c) { mContext = c; } @JavascriptInterface public void pushView(String title,String url) { Intent intent = new Intent(this, MainActivity.class); intent.putExtra("title", title); intent.putExtra("url", url); startActivity(intent); } }
需要注意的是pushView()方法就是js调用Android的方法,这个方法必须要在方法上面加上注解:@JavascriptInterface,不然js是无法调用pushView()这个方法的。
js代码如下:
AndroidFunction.pushView('评价',url);
转载时请注明出处及相应链接,本文永久地址:http://blog.it985.com/23199.html
微信打赏
支付宝打赏
感谢您对作者Bob的打赏,我们会更加努力! 如果您想成为作者,请点我
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- iOS 12 人机交互指南:交互(User Interaction)
- 生活NLP云服务“玩秘”站稳人机交互2.0语音交互场景
- asyncio之子进程交互
- 以太坊交互工具
- 学习 PixiJS — 交互工具
- Python基础(7)-用户交互
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
PHP for the World Wide Web, Second Edition (Visual QuickStart Gu
Larry Ullman / Peachpit Press / 2004-02-02 / USD 29.99
So you know HTML, even JavaScript, but the idea of learning an actual programming language like PHP terrifies you? Well, stop quaking and get going with this easy task-based guide! Aimed at beginning ......一起来看看 《PHP for the World Wide Web, Second Edition (Visual QuickStart Gu》 这本书的介绍吧!