关于Android中Java与Javascript之间的传值研究
?
public class WebViewDemo extends Activity { private WebView mWebView; private Handler mHandler = new Handler(); public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.webviewdemo); mWebView = (WebView) findViewById(R.id.webview); WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); mWebView.addJavascriptInterface(new Object() { public void clickOnAndroid() { mHandler.post(new Runnable() { public void run() { mWebView.loadUrl("javascript:wave()"); } }); } }, "demo"); mWebView.loadUrl("file:///android_asset/demo.html"); }}
?来分析一下这段代码:
WebSettings webSettings = mWebView.getSettings();webSettings.setJavaScriptEnabled(true);?首先生成一个WebSettings对象,其次setJavaScriptEnabled(true);通过这句声明使WebView能够支持JavaScript脚本。
<html> <script language="javascript"> function wave() { document.getElementById("droid").src="android_waving.png"; } </script> <body> <a onClick="window.demo.clickOnAndroid()"> <img id="droid" src="android_normal.png"/><br> Click me! </a> </body></html>?其中wave() 是被Java程序调用的。<aonClick="window.demo.clickOnAndroid()">通过点击来调用window.demo.clickOnAndroid()函数,这样就调用了Java的clickOnAndroid()方法。
?