1.main.xml
2.demo.html
A Demo ----Android and Javascript invoke each other. Author:Frankiewei
3.WebViewDemo.java
package com.tutor.webwiewdemo;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
public class WebViewDemo extends Activity {private WebView mWebView;private Button mButton;public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);setupViews();}//初始化private void setupViews() {mWebView = (WebView) findViewById(R.id.webview);WebSettings mWebSettings = mWebView.getSettings();//加上这句话才能使用Javascript方法mWebSettings.setJavascriptEnabled(true);//增加接口方法,让html页面调用mWebView.addJavascriptInterface(new Object() {//这里我定义了一个打开地图应用的方法public void startMap() {Intent mIntent = new Intent();ComponentName component = new ComponentName("com.google.android.apps.maps","com.google.android.maps.MapsActivity");mIntent.setComponent(component);startActivity(mIntent);}}, "demo");//加载页面mWebView.loadUrl("file:///android_asset/demo.html");mButton = (Button) findViewById(R.id.button);//给button添加事件响应,执行Javascript的fillContent()方法mButton.setOnClickListener(new Button.OnClickListener() {public void onClick(View v) {mWebView.loadUrl("Javascript:fillContent()");}});}
}
首界面 点击按钮时,html内容改变