WebView 是如何支持Javascript自定义对象,讲java对象绑定到一个JavaScript对象中,程序以启动就显示一个Html页面,在html页面中包含有javascript的脚本,该javascript脚本的执行是在java代码中执行的,
该例子是Android Html Javascript互相调用的例子:
package com.cmcc.webview.demo;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.Menu;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;
public class WebViewActivity extends Activity {
private WebView mWebView;
private Handler mHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebView = (WebView)findViewById(R.id.webView);
WebSettings webSetting = mWebView.getSettings();
webSetting.setJavaScriptEnabled(true);
mWebView.addJavascriptInterface(new Object(){
@SuppressWarnings("unused")
public void clickOnAndroid(){
mHandler.post(new Runnable(){
@Override
public void run() {
mWebView.loadUrl("javascript:wave()");
Toast.makeText(getApplicationContext(), "click()方法", Toast.LENGTH_LONG).show();
}
});
}
}, "click");
mWebView.loadUrl("file:///android_asset/demo.html");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
main.xml文件的内容:
<RelativeLayout 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"
tools:context=".WebViewActivity" >
<WebView
android:id="@+id/webView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
如果需要用到上网的时候在AndroidManifest.xml文件中添加上网的权限,这个我就不写了。
下面是Html页面中的内容:
<html>
<script language="javascript">
function wave() {
document.getElementById("android").src = "android_waving.png";
}
</script>
<body>
<a onClick="window.click.clickOnAndroid()"> <img id="android" src="android_normal.png" /><br> Click me!</a>
</body>
</html>