在android的界面同样可以用html而不用layout同时可以开启对js的支持操作界面显示数据
实列
在assets里面新建一个index.html文件在屏幕上显示一个列表
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
<title>Insert title here</title>
<script type="text/javascript">
function show(jsondata){//[{id:21,name:"xxx",mobile:"12332213"},{}] //接收一个字符串数组
var jsonobjs = eval(jsondata);
var table = document.getElementById("personTable");
for(var y=0; y<jsonobjs.length; y++){
var tr = table.insertRow(table.rows.length); //濞h濮炴稉锟筋攽
//濞h濮炴稉澶婂灙
var td1 = tr.insertCell(0);
var td2 = tr.insertCell(1);
td2.align = "center";
var td3 = tr.insertCell(2);
td3.align = "center";
//鐠佸墽鐤嗛崚妤�敶鐎圭懓鎷扮仦鐐达拷
td1.innerHTML = jsonobjs[y].id;
td2.innerHTML = jsonobjs[y].name;
td3.innerHTML = "<a href='javascript:itcast.call(\""+ jsonobjs[y].mobile+ "\")'>"+ jsonobjs[y].mobile+ "</a>";
}
}
</script>
</head>
<!-- js娴狅絿鐖滈柅姘崇箖webView鐠嬪啰鏁ら崗鑸靛絻娴犳湹鑵戦惃鍒痑va娴狅絿鐖�-->
<body οnlοad="javascript:itcast.getContacts()">
<table border="0" width="100%" id="personTable" cellspacing="0">
<tr>
<td width="20%">缂傛牕褰�/td><td width="40%" align="center">婵挸鎮�/td><td align="center">閻絻鐦�/td>
</tr>
</table>
<a href="javascript:window.location.reload()">閸掗攱鏌�/a>
</body>
</html>
Activity代码
package cn.itcast.html;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import cn.itcast.domain.Contact;
import cn.itcast.service.ContactService;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebView;
public class MainActivity extends Activity {
private WebView webview;
private ContactService contactService;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
contactService = new ContactService();
webview = (WebView)findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);//开启javascript支持
webview.addJavascriptInterface(new ContactPlugin(), "itcast");
// webview.loadUrl("file:///android_asset/index.html");//加载html文件
webview.loadUrl("http://192.168.1.10:8080/videoweb/index.html");
}
private class ContactPlugin{
public void getContacts(){
List<Contact> contacts = contactService.getContacts();//得到联系人数据
try {
JSONArray array = new JSONArray();
for(Contact contact : contacts){
JSONObject item = new JSONObject();
item.put("id", contact.getId());
item.put("name", contact.getName());
item.put("mobile", contact.getMobile());
array.put(item);
}
String json = array.toString();//转成json字符串
webview.loadUrl("javascript:show('"+ json +"')");//调用页面里面的javascript方法
} catch (JSONException e) {
e.printStackTrace();
}
}
public void call(String mobile){
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+ mobile));
startActivity(intent);
}
}
}