android中使用HTML作布局文件以及調用Javascript
在android開發中,通常使用xml格式來描述布局文件,采用Android的layout布局有時候根本滿足不了我們對于界面的要求,有時候沒有web頁面那樣炫。就目前而言,熟悉android布局及美化的人員少之又少,出現了嚴重的斷層。大部分企業,其實還是程序員自己動手布局。這樣既浪費時間和精力,也未必能達到理想的效果。但是,在企業級的android開發中,使用html頁面進行布局,也有很多的優勢(例如:簡單,大部分開發人員及美工都熟悉,方便統一進行更新,管理)。據筆者了解,已經有不少的公司在使用這種方式進行布局開發。這也可能是一種趨勢。
下面,我將給出一個實例代碼,供大家學習使用html頁面給android應用布局。
Step 1 :新建一個Android工程,命名為HtmlForUI
Step 2:在assets目錄下寫一個android.html文件,代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "; <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){// [{name:"xxx",amount:600,phone:"13988888"},{name:"bb",amount:200,phone:"1398788"}] var jsonobjs = eval(jsondata); // 將字符串string轉換成json var table = document.getElementById("personTable"); for(var y=0; y<jsonobjs.length; y++){ var tr = table.insertRow(table.rows.length); //添加一行 //添加3列 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].name; td2.innerHTML = jsonobjs[y].amount;td3.innerHTML = "<a href='javascript:contact.call(\""+ jsonobjs[y].phone+ "\")'>"+ jsonobjs[y].phone+ "</a>"; } }
</script> </head> <!-- 調用WebView設置的 webView.addJavascriptInterface(new JSObject(), "contact"); 插件contact中的java代碼 --> <body onload="javascript:contact.showcontacts()"> <table border="1" width="100%" id="personTable" cellspacing="0"> <tr> <td width="35%">姓名</td><td width="30%" align="center">存款</td><td align="center">電話</td> </tr> </table> <a href="javascript:window.location.reload()">刷新</a> <a href="javascript:contact.startNewActivity()">跳轉</a> </body>
</html></pre>
Step 3:編寫該應用用到的用戶實體類Contact.java和業務邏輯類 ContactService.java的代碼如下:Contact.java
package cn.roco.domain;public class Contact { private Integer id; private String name; private String phone; private Integer amount;
public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Integer getAmount() { return amount; } public void setAmount(Integer amount) { this.amount = amount; } public Contact(Integer id, String name, String phone, Integer amount) { this.id = id; this.name = name; this.phone = phone; this.amount = amount; }
}</pre>
ContactServiceContactService.java
package cn.roco.service;import java.util.ArrayList; import java.util.List;
import cn.roco.domain.Contact;
public class ContactService { /**
* 具體業務可以取本地數據庫中的數據 也可以從遠程服務器獲取數據 */ public List<Contact> getContacts(){ List<Contact> contacts=new ArrayList<Contact>(); for (int i = 1; i <= 15; i++) { contacts.add(new Contact(i, "Roco_"+i, "09408400"+i, 1000+i)); } return contacts; }
}</pre>
Step4: 我們需要一個類來加載html頁面以及javascript的調用Step4: 我們需要一個類來加載html頁面以及javascript的調用MainActivity.java
package cn.roco.view.html;import java.util.List;
import org.json.JSONArray; import org.json.JSONObject;
import cn.roco.domain.Contact; import cn.roco.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; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); /** android內置瀏覽器對象 */ webView = (WebView) this.findViewById(R.id.webView); /** * 加載放在assets目錄下的android.html文件 注意url的地址前綴為: file:///android_asset/ * * 其實可以把這個html布局文件放在公網中,這樣方便隨時更新維護 例如 * webview.loadUrl("http://192.168.1.100:8080/Hello/index.html"); */ webView.loadUrl("file:///android_asset/android.html"); /** 允許javascript的運行 */ webView.getSettings().setJavaScriptEnabled(true); /** * 添加一個js交互接口,方便html布局文件中的javascript代碼能與后臺java代碼直接交互訪問 * "contact"為給該對象取得別名 對應android.html中的contact */ webView.addJavascriptInterface(new ContactPlugin(), "contact");// new類名,交互訪問時使用的別名 contactService = new ContactService(); } /** * 自定義的javascript對象 */ private final class ContactPlugin { /** * 對應: <body onload="javascript:contact.showcontacts()"> */ public void showcontacts() { try { // 獲得List數據集合 List<Contact> contacts = contactService.getContacts(); // 將List泛型集合的數據轉換為JSON數據格式 JSONArray jsonArray = new JSONArray(); for (Contact contact : contacts) { JSONObject jsonObject = new JSONObject(); jsonObject.put("name", contact.getName()); jsonObject.put("amount", contact.getAmount()); jsonObject.put("phone", contact.getPhone()); jsonArray.put(jsonObject); } // 轉換成json字符串 String json = jsonArray.toString(); /** 調用android.html中的show()方法 */ webView.loadUrl("javascript:show('" + json + "')"); } catch (Exception e) { e.printStackTrace(); } } /** * 對應: td3.innerHTML = "<a href='javascript:contact.call(\""+ * jsonobjs[y].phone+ "\")'>"+ jsonobjs[y].phone+ "</a>"; */ public void call(String phone) { /** * 調用撥號程序 */ Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone)); startActivity(intent); } public void startNewActivity() { Intent intent = new Intent(MainActivity.this, NewActivity.class); startActivity(intent); } }
}</pre>
在html頁面中,我們可以點擊超鏈接跳轉到android中的Activity去,我們新建一個NewActivity
package cn.roco.view.html;import android.app.Activity; import android.os.Bundle;
public class NewActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.msg); }
}</pre>
step5:將上面兩個Activity的布局文件寫好main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="<WebView android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/webView" />
</LinearLayout></pre>
msg.xml
<?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"> <TextView android:text="這是一個新的Activity" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout>
step6:部署文件<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="<uses-permission android:name="android.permission.CALL_PHONE" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".MainActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".NewActivity" /> </application>
</manifest></pre>
step7:運行效果如下圖所示
點擊電話超鏈接可以激活撥號系統:
點擊跳轉按鈕可以激活新的Activity
來自:http://blog.csdn.net/qq446282412/article/details/8788765