下面提供一个演示的例子,代码如下:
- package com.aloong.map;
- import android.app.Activity;
- import android.os.Bundle;
- import android.os.Handler;
- import android.webkit.WebSettings;
- import android.webkit.WebView;
- 9public class MyMap extends Activity {
- private static String TAG = MyMap.class.getName();
- private WebView mWebView;
- private Handler mHandler;
- private WebSettings mWebSettings;
- /** *//** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- mWebView = (WebView) this.findViewById(R.id.webview);
- mHandler = new Handler();
- // 设置支持JavaScript等
- mWebSettings = mWebView.getSettings();
- mWebSettings.setJavaScriptEnabled(true);
- mWebSettings.setBuiltInZoomControls(true);
- mWebSettings.setLightTouchEnabled(true);
- mWebSettings.setSupportZoom(true);
- mWebView.setHapticFeedbackEnabled(false);
- // mWebView.setInitialScale(0); // 改变这个值可以设定初始大小
- //重要,用于与页面交互!
- mWebView.addJavascriptInterface(new Object() {
- @SuppressWarnings("unused")
- public void oneClick(final String locX, final String locY) {//此处的参数可传入作为js参数
- mHandler.post(new Runnable() {
- public void run() {
- mWebView.loadUrl("javascript:shows(" + locX + "," + locY + ")");
- }
- });
- }
- }, "demo");//此名称在页面中被调用,方法如下:
- //<body onClick="window.demo.clickOnAndroid(event.pageX,event.pageY)">
- final String mimeType = "text/html";
- final String encoding = "utf-8";
- final String html = "";// TODO 从本地读取HTML文件
- mWebView.loadDataWithBaseURL("file:///sdcard/", html, mimeType,
- encoding, "");
- }
- }
运行以上代码,就可以在程序中打开自己写的html页面.并且实现Java与JavaScript的双向交互.
我们甚至可以在页面中使用JQuery之类的框架制作出很好看的效果,而这比写Android代码我觉得简单多了.