Activity代码
public class JSandJavaActivity extends Activity {
WebView webView= null;
Handler handler = new Handler();//进行异步通讯
@Override
public void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webView = (WebView) this.findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);//只有设为true才能与javascript进行通讯
webView.addJavascriptInterface(new
Object(){//让javascript能调用java中的方法
public
void show(){
handler.post(new
Runnable(){
@Override
public
void run() {
//webView.loadUrl("javascript:pageini()");
webView.loadUrl("javascript:personlist('"+query()+"')");//调用javascript函数
}
});
}
}, "caller");
String path="file:///android_asset/test.html";
webView.loadUrl(path);//载入页面
}
public
static String query(){//构造json对象
JSONArray array = null;
try {
JSONObject
object = new JSONObject();
object.put("id",
1);
object.put("name","lybeen");
object.put("age",
23);
object.put("address",
"HZ");
JSONObject
object2 = new JSONObject();
object2.put("id",
2);
object2.put("name","lybeen2");
object2.put("age",
24);
object2.put("address",
"SH");
array = new
JSONArray();
array.put(object);
array.put(object2);
} catch (JSONException e)
{
// TODO
Auto-generated catch block
e.printStackTrace();
}
return array.toString();
}
}
HTML代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML
1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=utf-8" />
<title>无标题文档</title>
<script
language="javascript">
function
personlist(jsons){ //传json对象
var
table=document.getElementByIdx_x("person");
var
arr=eval_r(jsons);
for(var
i=0;i<arr.length;i++){
var
jsonobj = arr[i];
var
tr = table.insertRow(table.rows.length);
var
td1 = tr.insertCell(0);
var
td2 = tr.insertCell(1);
var
td3 = tr.insertCell(2);
var
td4 = tr.insertCell(3);
td1.innerHTML
= jsonobj.id;
td2.innerHTML
= jsonobj.name;
td3.innerHTML
= jsonobj.age;
td4.innerHTML
= jsonobj.address;
}
}
</script>
</head>
<body onload="caller.show()">
//调用java中的函数
<table width="100%"
id="person">
<tr
bgcolor="#33FFFF">
<td>id</td>
<td>name</td>
<td>age</td>
<td>address</td>
</tr>
<!-- <a onclick="window.caller.show()">click
me</a> -->
</table>
</body>
</html>