通过WebView,可以在JavaScript代码和客户端的Android代码间创建接口。例如,Android可以获取JavaScript里的输入。为了在你的JavaScript和Android代码间绑定一个新的接口,需要调用addJavascriptInterface(),传给它一个类实例来绑定到JavaScript,还需要一个接口名让JavaScript可以调用,以便来访问类。下面举个简单例子;
html文件:
<!DOCTYPE HTML>
<html xmlns=”http://www.w3.org/1999/xhtml” debug=”true”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″/>
<meta name=”viewport”
content=”width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0″>
<meta name=”apple-mobile-web-app-capable” content=”yes”>
<meta name=”viewport” content=”target-densitydpi=device-dpi”/>
<script type=”text/javascript”>
function init()
{
var testVal = document.getElementById(‘mytextId’).value;
AndroidFunction.showToast(testVal);
}
</script>
</head>
<body>
<div style=”float: left;width: 50%;”>
<input type=”text” style=”width: 180px;”
name=”myText” id=”mytextId”/>
</div>
<div style=”clear: both;height: 3px;”></div>
<div>
<input value=”submit” type=”button” name=”submit”
id=”btnSubmit” onclick=”javascript:return init();”/>
</div>
</body>
</html>
android布局xml文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.zmit.webview.MainActivity"></pre>
<pre> <WebView
android:id="@+id/wv1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.5"
/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:layout_weight="1">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout></pre>
<pre></LinearLayout>
代码:
public class MainActivity extends AppCompatActivity {
WebView wView;
private TextView myTextView;
final Handler myHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wView = (WebView) findViewById(R.id.wv1);
myTextView = (TextView) findViewById(R.id.textView1);
final JavaScriptInterface myJavaScriptInterface
= new JavaScriptInterface(this);//交互接口
wView.getSettings().setJavaScriptEnabled(true);
wView.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
wView.loadUrl("file:///android_asset/untitled.html");
}
public class JavaScriptInterface {
Context mContext;
JavaScriptInterface(Context c) {
mContext = c;
}
@JavascriptInterface
public void showToast(String webMessage){
final String msgeToast = webMessage;
myHandler.post(new Runnable() {
@Override
public void run() {
myTextView.setText(msgeToast);
}
});
Toast.makeText(mContext, webMessage, Toast.LENGTH_SHORT).show();
}
}
}
效果如下所示