在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) + "')");