Android 使用HTML布局页面
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript"> function show(jsondata) { var jsonobj = eval(jsondata); var table = document.getElementById("ids"); for ( var y = 0; y < jsonobj.length; y++) { var tr = table.insertRow(table.rows.length); var td1 = tr.insertCell(0); var td2 = tr.insertCell(1); var td3 = tr.insertCell(2); td1.innerHTML = jsonobj[y].name; td2.innerHTML = jsonobj[y].amount; td3.innerHTML = "<a href='javascript:contact.call(\"" + jsonobj[y].phone + "\")'>" + jsonobj[y].phone + "</a>";<!-- 调用javascript中contact对象的call(String)方法 --> } } </script> </head> <body onload="javascript:contact.showAll()"><!-- javascript中的一个对象,对象名为contact,其实包含一个方法showAll() --> <table id="ids"> <tr> <td width="35%">姓名</td> <td width="35%">存款</td> <td align="center">电话</td> </tr> </table> <a href="javascript:window.location.reload()">刷新</a> </body> </html>
1.以上是布局页面!
2.在MainActivity对应的Layout文件中,添加一个WebView控件,用于显示上面的html;
3.获取数据源的两个类:
public class BeanService { public List<Bean> getBeans() { List<Bean> list = new ArrayList<Bean>(); list.add(new Bean(1, "1", "138837416xx", "123")); list.add(new Bean(2, "2", "138837416xx", "456"));// public Bean(Integer id, String name, String phone, String amount) return list; } }
4.修改MainActivity:
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); WebView wv = (WebView) findViewById(R.id.wv); wv.loadUrl("file:///android_asset/index.html");// 加载assets文件夹中的index.html wv.getSettings().setJavaScriptEnabled(true);// 设置Javascript可用 wv.addJavascriptInterface(new Jsobj(wv), "contact");// 向WebView中注入名为contact的对象 } private final class Jsobj { private WebView wv; public Jsobj(WebView v) { this.wv = v; } public void call(String phone) {// 拨打电话方法 Intent i = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone)); startActivity(i); } public void showAll() {// 显示所有的数据信息 List<Bean> list = new BeanService().getBeans(); JSONArray arr = new JSONArray(); for (Bean b : list) { JSONObject obj = new JSONObject(); try { obj.put("name", b.getName()); obj.put("amount", b.getAmount()); obj.put("phone", b.getPhone()); arr.put(obj); } catch (JSONException e) { e.printStackTrace(); } } String json = arr.toString(); wv.loadUrl("javascript:show('" + json + "')");// 调用webview中的show(Jsonobj)方法-javascript方法 } } }