android webview数据交互
2016-05-23 12:42
274 查看
在android应用开发中难免会遇到webview交互问题,在webview中显示数据,及回调java代码。
一、js中调用java代码
1、设置webview使用javascript:webView.getSetting().setJavaScriptEnable(ture),注意此方法中api17以后需要设置了@JavascriptInterface注解的方法才可以在被调用。
2、将封装的对象放入到webview中:webView.addJavascriptInterface(对象, webview中对象别名);
3、在js中调用java代码:别名.方法名()
二、java中调用js代码
1、使用webview.load(js中的方法名);
2、显示json数据:
1、使用原生的JsonObject封装数据
2、使用Gson将对象转换成json字符串
注意:1、将json字符串传入到webview中是需要加单引号:mView.loadUrl("javascript:showData('" + gson.toJson(student) + "')");
2、在html中解析json字符串:使用eval表达式解析:var data=eval("("+json+")");
3、显示数据:获取元素之后设置innerText属性即可
三、关键代码:
1、html:
function showData(json){
test.shotInfo(json);
var data=eval("("+json+")");
document.getElementById("count").innerText=data.count;
ocument.getElementById("title").innerText=data.title;
}
2、java代码:
Student student=new Student();
student.setCount(100);
student.setTitle("你大爷的");
Gson gson=new Gson();
mView.loadUrl("javascript:showData('" + gson.toJson(student) + "')");
一、js中调用java代码
1、设置webview使用javascript:webView.getSetting().setJavaScriptEnable(ture),注意此方法中api17以后需要设置了@JavascriptInterface注解的方法才可以在被调用。
2、将封装的对象放入到webview中:webView.addJavascriptInterface(对象, webview中对象别名);
3、在js中调用java代码:别名.方法名()
二、java中调用js代码
1、使用webview.load(js中的方法名);
2、显示json数据:
1、使用原生的JsonObject封装数据
2、使用Gson将对象转换成json字符串
注意:1、将json字符串传入到webview中是需要加单引号:mView.loadUrl("javascript:showData('" + gson.toJson(student) + "')");
2、在html中解析json字符串:使用eval表达式解析:var data=eval("("+json+")");
3、显示数据:获取元素之后设置innerText属性即可
三、关键代码:
1、html:
function showData(json){
test.shotInfo(json);
var data=eval("("+json+")");
document.getElementById("count").innerText=data.count;
ocument.getElementById("title").innerText=data.title;
}
2、java代码:
Student student=new Student();
student.setCount(100);
student.setTitle("你大爷的");
Gson gson=new Gson();
mView.loadUrl("javascript:showData('" + gson.toJson(student) + "')");
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories