日期:2014-05-16 浏览次数:20336 次
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <SCRIPT LANGUAGE="JavaScript"> <!-- function contactlist(jsons){ var table=document.getElementById("contactTable");//获得html中Table var arr = eval(jsons);//将jsons字符串转换为json对象数组 for(var i=0;i < arr.length;i++){ var jsonObj = arr[i]; var tr = table.insertRow(table.rows.length);//添加tr var td1 = tr.insertCell(0);//td var td2 = tr.insertCell(1); td2.align = "center"; var td3 = tr.insertCell(2); td1.innerHTML = jsonObj.id;//设置每列对应的值 td2.innerHTML = jsonObj.name; td3.innerHTML = jsonObj.phone; } } //--> </SCRIPT> <BODY onload="javascript:myjavascript.show()"> <table width="100%" border="0" cellspacing="0" id="contactTable"> <tr> <td width="20%">编号</td> <td width="center">姓名</td> <td width="30%">电话</td> </tr> </table> </BODY> </HTML>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <WebView android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/webview" /> </LinearLayout>
/** * HTML ui类 */ public class HtmlUIActivity extends Activity { private WebView webView; private Handler handler = new Handler(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); webView = (WebView)findViewById(R.id.webview); //重要:让webview支持javascript webView.getSettings().setJavaScriptEnabled(true); //重要:添加可以供html中可供javascript调用的接口类 webView.addJavascriptInterface(new MyJavaScript(this, handler), "myjavascript"); //加载index.html webView.loadUrl("file:///android_asset/index.html"); } }
public class MyJavaScript { private WebView webview; //使用一个handler来处理加载事件 private Handler handler; public MyJavaScript(Context context,Handler handler){ this.handler = handler; webview = (WebView) ((Activity)context).findViewById(R.id.webview); } /* * java调用显示网页,异步 */ public void show(){ handler.post(new Runnable() { public void run() { 重要:url的生成,传递数据给网页 String url = "javascript:contactlist('" + generateData() + "')"; webview.loadUrl(url); } }); } /* * 由java程序生成数据传到网页中显示 */ private String generateData(){ try { //构造一个json对象 JSONObject obj1 = new JSONObject(); obj1.put("id", 12); obj1.put("name", "tom"); obj1.put("phone", "66666666"); JSONObject obj2 = new JSONObject(); obj2.put("id", 13); obj2.put("name", "jerry"); obj2.put("phone", "88888888"); //将构造好的2个json对象加入到json数组中 JSONArray arr = new JSONArray(); arr.put(obj1); arr.put(obj2); return arr.toString(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ""; }