Androd Html Demo js与java相互调用

sample demo

1.首先创建一个简单的android工程

2.修改layout文件main.xml
<?xml version="1.0" encoding="utf-8"?>  
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:orientation="vertical" >  
      
    <WebView
        android:id="@+id/web"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
    />
    
    <LinearLayout 
       android:orientation="vertical"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:layout_weight="1"
       android:gravity="bottom|right">
      
        <Button
		android:layout_height="wrap_content"
		android:id="@+id/Button_Send"
		android:text="javatojs"
		android:layout_width="400px"/>
     </LinearLayout>
</RelativeLayout> 


3.创建activity java类
package com.example.myandroidproj;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.Button;
import android.util.Log;


public class IChartJsDemoActivity extends Activity {
	
	private String TGA="IChartJsDemoActivity";
	private WebView webView;
	private Button send;
	private Handler handler;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		initUI();
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.ichart_js_demo, menu);
		return true;
	}

	@SuppressLint("JavascriptInterface")
	public void initUI(){
		handler = new Handler();
		
		webView = (WebView)this.findViewById(R.id.web);
		webView.getSettings().setBuiltInZoomControls(true);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.loadUrl("file:///android_asset/index.html");
		//放置页面js对象
		webView.addJavascriptInterface(new AndroidJsTool(), "androidJsTool");
		
		send = (Button) this.findViewById(R.id.Button_Send);
		send.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				JSONArray arr =new JSONArray();
				for(int i=0;i<10;i++){
					JSONObject json =new JSONObject(); 
					 try {
						json.put("name", "jasion");
						json.put("country", "中国");
						json.put("mobile", "1882529831"+i);
						arr.put(json);
					} catch (JSONException e) {
						Log.e(TGA, e.getMessage());
						e.printStackTrace();
					}
					
				}
				String paramStr = arr.toString();
				//java 调用js
				webView.loadUrl("javascript:initData("+paramStr+")");
			}
			
		});
	}
	
	final class AndroidJsTool{
		//必须要加上这个注释,要不然html页面就访问不到这个方法
		@JavascriptInterface
		public void runOnAndroidJavaScript(final String str){
			handler.post(new Runnable(){
				public void run() {
					//测试js调用java
					Log.i(TGA, "hello world:"+str);
				}
			});
		}
	}
}


4.创建html文件 index.html,index.html文件要放在工程目录底下的assets里面
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
</script>
</head>
<body>
	<table id="personTable">
		<tr>
			<td style="color:blue;">名称</td>
			<td style="color:blue;">国家</td>
			<td style="color:blue;">电话</td>
		</tr>
	</table>
	<input type="text" id="wordsInput" /><br/>
	<input type="button" id="sayWords" onclick="sayWord()" value="send to java" />
</body>

<script>
function sayWord(){
	var words=document.getElementById("wordsInput").value;
	androidJsTool.runOnAndroidJavaScript(words);//调用android的函数
}

function initData(jsonData){
	var jsonobjs = eval(jsonData);  
	var table = document.getElementById("personTable");  
	for(var y=0; y<jsonobjs.length; y++){  
            var tr = table.insertRow(table.rows.length); //添加一行  
            //添加三列  
            var td1 = tr.insertCell(0);  
            var td2 = tr.insertCell(1);  
            td2.align = "center";  
            var td3 = tr.insertCell(2);  
            td3.align = "center";  
            //设置列内容和属性  
            td1.innerHTML = jsonobjs[y].name;   
            td2.innerHTML = jsonobjs[y].country;   
            td3.innerHTML = jsonobjs[y].mobile;   
        } 
}
</script>
</html>

你可能感兴趣的:(html,android,java2js,js2java)