之前的时候做过Android和Html之间的调用,时间已久就有点遗忘了,现在回头看一下,顺便做一下记录。
Android调用网页的形式主要是采用控件WebView来实现的。
1.首先要布局上一个WebView控件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<WebView
android:id="@+id/act_html_webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
2.在Activiry中获取此控件,并且设置这个控件的属性
@SuppressLint("SetJavaScriptEnabled")
private void initView() {
// 加载页面
webView = (WebView) findViewById(R.id.act_html_webview);
WebSettings ws = webView.getSettings();
ws.setJavaScriptEnabled(true);
ws.setSupportZoom(true);
ws.setBuiltInZoomControls(true);
ws.setUseWideViewPort(true);// 设置此属性,可任意比例缩放。
// 自适应屏幕
ws.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
ws.setLoadWithOverviewMode(true);
String htmlFile = "file:///android_asset/" + table.htmlName;
webView.loadUrl(htmlFile);
// 在js中调用本地java方法
webView.addJavascriptInterface(new JsInterface(this), "AndroidWebView");
// 添加客户端支持
webView.setWebChromeClient(new WebChromeClient());
}
3.编写中间类 JsInterface
private class JsInterface {
private Context mContext;
public JsInterface(Context context) {
this.mContext = context;
}
// 在js中调用window.AndroidWebView.getHtmlValue(name),便会触发此方法。
@JavascriptInterface
// 这个声明很重要 如果target 大于等于API 17,则需要加上如下注解
public String getHtmlValue(String value) {
Toast.makeText(mContext, value, Toast.LENGTH_SHORT).show();
return value;
}
@JavascriptInterface
public String getAllValues(String value) {
htmlValue = saveToDB(value);// 得到网页中填写的数据
Intent intent = new Intent();
intent.putExtra("TABLE_NAME", table.tableName);
setResult(102, intent);
finish();
return value;
}
}
4.编写Html文件
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>Android WebView 与 Javascript 交互</title>
<head>
<style>
body {background-color:#e6e6e6}
.rect
{
color:white;
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:16px;
width:100px;
padding:6px;
background-color:#98bf21;
text-decoration:none;
text-align:center;
border:none;
cursor:pointer;
}
.inputStyle {font-size:18px;padding:6px;;
border-bottom: 1px solid black;
margin: 0px;
padding: 0px;
background:url(0) no-repeat;
border-top :none;
border-left :none;
border-right :none;
}
.textareaStyle {font-size:18px;padding:6px;;
border-bottom: 1px solid black;
margin: 0px;
padding: 0px;
background:url(0) no-repeat;
border-top :none;
border-left :none;
border-right :none;
resize :none;
overflow-x :hidden;
overflow-y :hidden
}
.labelStyle{
line-height:50px;
font-size:20px;
font-family:楷体_GB2312;
}
#textarea {
display: block;
margin:0 auto;
overflow: hidden;
width: 550px;
font-size: 14px;
height: 18px;
line-height: 24px;
padding:2px;
}
textarea {
outline: 0 none;
border-color: rgba(82, 168, 236, 0.8);
}
</style>
</head>
<body>
<p align="center" style='font-size:30px'>作 业 笔 录</p>
<div class="form-group">
<label class="sr-only" for="account" >时间:</label>
<textarea id="id_Inquir1_1" class="textareaStyle" rows=1 cols= 4 onclick="javascript:autoTextarea(this);" ></textarea>
<label class="sr-only" for="account" >年</label>
<textarea id="id_Inquir1_2" class="textareaStyle" rows=1 cols= 2 onclick="javascript:autoTextarea(this);" ></textarea>
<label class="sr-only" for="account" >月</label>
<textarea id="id_Inquir1_3" class="textareaStyle" rows=1 cols= 2 onclick="javascript:autoTextarea(this);" ></textarea>
<label class="sr-only" for="account" >日</label>
<textarea id="id_Inquir1_4" class="textareaStyle" rows=1 cols= 2 onclick="javascript:autoTextarea(this);" ></textarea>
<label class="sr-only" for="account" >时</label>
<textarea id="id_Inquir1_5" class="textareaStyle" rows=1 cols= 2 onclick="javascript:autoTextarea(this);" ></textarea>
<label class="sr-only" for="account" >分至</label>
<textarea id="id_Inquir1_6" class="textareaStyle" rows=1 cols= 2 onclick="javascript:autoTextarea(this);" ></textarea>
<label class="sr-only" for="account" >时</label>
<textarea id="id_Inquir1_7" class="textareaStyle" rows=1 cols= 2 onclick="javascript:autoTextarea(this);" ></textarea>
<label class="sr-only" for="account" >分结束</label>
</div>
<div class="form-group">
<label class="sr-only" for="account" >地点:</label>
<textarea id="id_Inquir1_8" class="textareaStyle" rows=1 cols= 80 onclick="javascript:autoTextarea(this);" ></textarea>
</div>
<div class="form-group">
<label class="sr-only" for="account" >人物:</label>
<textarea id="id_Inquir1_9" class="textareaStyle" rows=1 cols= 80 onclick="javascript:autoTextarea(this);" ></textarea>
</div>
<div class="form-group">
<label class="sr-only" for="account" >记录人:</label>
<textarea id="id_Inquir1_10" class="textareaStyle" rows=1 cols= 80 onclick="javascript:autoTextarea(this);" ></textarea>
</div>
<div class="form-group">
<label class="sr-only" for="account" >被询问人姓名:</label>
<textarea id="id_Inquir1_11" class="textareaStyle" rows=1 cols= 10 onclick="javascript:autoTextarea(this);" ></textarea>
<label class="sr-only" for="account" > 性别:</label>
<textarea id="id_Inquir1_12" class="textareaStyle" rows=1 cols= 2 onclick="javascript:autoTextarea(this);" ></textarea>
<label class="sr-only" for="account" > 年龄:</label>
<textarea id="id_Inquir1_13" class="textareaStyle" rows=1 cols= 3 onclick="javascript:autoTextarea(this);" ></textarea>
<label class="sr-only" for="account" > 民族:</label>
<textarea id="id_Inquir1_14" class="textareaStyle" rows=1 cols= 20 onclick="javascript:autoTextarea(this);" ></textarea>
</div>
<div class="form-group">
<label class="sr-only" for="account" >文化程度:</label>
<textarea id="id_Inquir1_15" class="textareaStyle" rows=1 cols= 10 onclick="javascript:autoTextarea(this);" ></textarea>
<label class="sr-only" for="account" > 职业:</label>
<textarea id="id_Inquir1_16" class="textareaStyle" rows=1 cols= 30 onclick="javascript:autoTextarea(this);" ></textarea>
<label class="sr-only" for="account" > 工作单位:</label>
<textarea id="id_Inquir1_17" class="textareaStyle" rows=1 cols= 30 onclick="javascript:autoTextarea(this);" ></textarea>
</div>
<div class="form-group">
<label class="sr-only" for="account" >住址:</label>
<textarea id="id_Inquir1_18" class="textareaStyle" rows=1 cols= 40 onclick="javascript:autoTextarea(this);" ></textarea>
<label class="sr-only" for="account" > 联系电话:</label>
<textarea id="id_Inquir1_19" class="textareaStyle" rows=1 cols= 20 onclick="javascript:autoTextarea(this);" ></textarea>
</div>
<script>
/**
* 文本框根据输入内容自适应高度
* @param {HTMLElement} 输入框元素
* @param {Number} 设置光标与输入框保持的距离(默认0)
* @param {Number} 设置最大高度(可选)
*/
var autoTextarea = function (elem, extra, maxHeight) {
extra = extra || 0;
var isFirefox = !!document.getBoxObjectFor || 'mozInnerScreenX' in window,
isOpera = !!window.opera && !!window.opera.toString().indexOf('Opera'),
addEvent = function (type, callback) {
elem.addEventListener ?
elem.addEventListener(type, callback, false) :
elem.attachEvent('on' + type, callback);
},
getStyle = elem.currentStyle ? function (name) {
var val = elem.currentStyle[name];
if (name === 'height' && val.search(/px/i) !== 1) {
var rect = elem.getBoundingClientRect();
return rect.bottom - rect.top -
parseFloat(getStyle('paddingTop')) -
parseFloat(getStyle('paddingBottom')) + 'px';
};
return val;
} : function (name) {
return getComputedStyle(elem, null)[name];
},
minHeight = parseFloat(getStyle('height'));
elem.style.resize = 'none';
var change = function () {
var scrollTop, height,
padding = 0,
style = elem.style;
if (elem._length === elem.value.length) return;
elem._length = elem.value.length;
if (!isFirefox && !isOpera) {
padding = parseInt(getStyle('paddingTop')) + parseInt(getStyle('paddingBottom'));
};
scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
elem.style.height = minHeight + 'px';
if (elem.scrollHeight > minHeight) {
if (maxHeight && elem.scrollHeight > maxHeight) {
height = maxHeight - padding;
style.overflowY = 'auto';
} else {
height = elem.scrollHeight - padding;
style.overflowY = 'hidden';
};
style.height = height + extra + 'px';
scrollTop += parseInt(style.height) - elem.currHeight;
document.body.scrollTop = scrollTop;
document.documentElement.scrollTop = scrollTop;
elem.currHeight = parseInt(style.height);
};
};
addEvent('propertychange', change);
addEvent('input', change);
addEvent('focus', change);
change();
};
function sendInfoToJava(){
//调用android程序中的方法,并传递参数
var name = document.getElementById("name_input1").value;
window.AndroidWebView.showInfoFromJs(name);
}
//在android代码中调用此方法
function showInfoFromJava(msg){
alert("来自网页的信息:"+msg);
}
function getHtmlValue(){
var name = document.getElementById("name_input3").value;
window.AndroidWebView.getHtmlValue(name);
}
function getValues(){
//获取ID为cargetdate下面的input为text的ID和value,如果是页面所有的input则将document.getElementById("cargetdate")换为document即可
//var list=document.getElementById("cargetdate").getElementsByTagName("input");
var list=document.getElementsByTagName("textarea");
var strData="";
//对表单中所有的input进行遍历
for(var i=0;i<list.length && list[i];i++) {
//判断是否为文本框
//if(list[i].type=="text"&&list[i].id!="subEmail") {
strData +=list[i].id+":"+list[i].value+";";
//}
}
window.AndroidWebView.getAllValues(strData);
}
function setValues(){
var result = window.AndroidWebView.getValuesFromDB();
var obj = eval("("+result+")");//解析json字符串
var list=document.getElementsByTagName("textarea");
for(var i=0;i<list.length && list[i];i++) {
var user=obj[i];
list[i].value = user.value;
//list[i].value = "123";
}
}
</script>
</body>
</html>
总结:以上就是Android和JS互相调用的过程。其中代码中的注释已经注释的很明白了,是在原来的代码的基础之上略加修改。