我的Android进阶之旅------>Android中使用HTML作布局文件以及调用Javascript

简介:     在android开发中,通常使用xml格式来描述布局文件,采用Android的layout布局有时候根本满足不了我们对于界面的要求,有时候没有web页面那样炫。

    在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" "http://www.w3.org/TR/html4/loose.dtd">
<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>


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;
	}

}


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;
	}
}


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);
		}

	}

}

 

在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);

	}
}


step5:将上面两个Activity的布局文件写好

main.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">
	
	<WebView android:layout_width="fill_parent"
		android:layout_height="fill_parent" android:id="@+id/webView" />
</LinearLayout>


 

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="http://schemas.android.com/apk/res/android"
	package="cn.roco.view.html" android:versionCode="1"
	android:versionName="1.0">
	<uses-sdk android:minSdkVersion="8" />

	<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>


 

step7:运行效果如下图所示

点击电话超链接可以激活拨号系统:

点击跳转按钮可以激活新的Activity

 


==================================================================================================

  作者:欧阳鹏  欢迎转载,与人分享是进步的源泉!

  转载请保留原文地址http://blog.csdn.net/ouyang_peng

==================================================================================================


相关文章
|
28天前
|
Java
有关Java发送邮件信息(支持附件、html文件模板发送)
有关Java发送邮件信息(支持附件、html文件模板发送)
26 1
|
1月前
如何在HTML文件中添加超链接
如何在HTML文件中添加超链接
21 0
|
1月前
|
Python
DTL与普通的HTML文件的区别
DTL与普通的HTML文件的区别。
67 5
N..
|
29天前
|
移动开发 前端开发 JavaScript
HTML文件
HTML文件
N..
13 1
|
6天前
|
JavaScript 前端开发
js怎么删除html元素
js怎么删除html元素
21 10
|
15天前
|
JSON JavaScript 前端开发
js是什么、html、css
js是什么、html、css
|
21天前
|
人工智能 前端开发 JavaScript
【前端设计】HTML+CSS+JavaScript基本特性
【前端设计】HTML+CSS+JavaScript基本特性
|
1月前
|
JavaScript 计算机视觉
纯js实现人脸识别眨眨眼张张嘴案例——index.html
纯js实现人脸识别眨眨眼张张嘴案例——index.html
16 0
|
1月前
|
PHP Python
通过html实现文件的上传和下载
通过html实现文件的上传和下载
|
1月前
|
前端开发 JavaScript
从0到1:用HTML、CSS和JavaScript构建一个简单的待办事项列表
从0到1:用HTML、CSS和JavaScript构建一个简单的待办事项列表
26 0