安卓笔记侠

专注安卓开发

导航

Java调用JavaScript

1.main.xml

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:orientation="vertical"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    >  
    <TextView    
        android:layout_width="fill_parent"   
        android:layout_height="wrap_content"   
        android:text="Welcome to Mr Wei's Blog."  
        />  
    <WebView  
        android:id="@+id/webview"  
        android:layout_width="fill_parent"   
        android:layout_height="wrap_content"   
    />  
    <Button  
        android:id="@+id/button"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:text="Change the webview content"  
    />  
</LinearLayout> 

2.demo.html

<html>  
    <mce:script language="javascript"><!--  
   
        function fillContent(){  
            document.getElementById("content").innerHTML =   
                 "This Content is showed by Android invoke Javascript function.";  
        }  
      
// --></mce:script>    
  <body>  
    <p><a onClick="window.demo.startMap()" href="">Start GoogleMap</a></p>  
    <p id="content"></p>  
    <p>A Demo ----Android and Javascript invoke each other.</p>  
    <p>Author:Frankiewei</p>  
  </body>  
</html>

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内容改变

 

  

  

posted on 2016-10-23 17:00  安卓笔记侠  阅读(715)  评论(0编辑  收藏  举报