下面是MainActivity.java
package com.example.webviewtest; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; public class MainActivity extends Activity { WebView wv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); wv=(WebView) findViewById(R.id.wv); wv.setWebViewClient(new WebViewClient()); //打开指定的页面 //wv.loadUrl("http://www.baidu.com"); // wv.loadUrl("file:///android_asset/a.html"); //wv.loadData(data, mimeType, encoding); // wv.loadUrl("http://f.hiphotos.baidu.com/image/h%3D200/sign=650d5402a318972bbc3a07cad6cd7b9d/9f2f070828381f305c3fe5bfa1014c086e06f086.jpg"); initData(); } class My extends Handler{} private void initData() { wv=(WebView) findViewById(R.id.wv); wv.setWebViewClient(new WebViewClient());//防止跳转到手机浏览器 WebSettings settings = wv.getSettings(); settings.setJavaScriptEnabled(true);启用javascript //指定可供js调用的java对象 wv.addJavascriptInterface(new A(), "bridge"); wv.loadUrl("file:///android_asset/a.html"); //打开指定的页面 //wv.loadUrl("http://www.baidu.com"); // wv.loadUrl("file:///android_asset/a.html"); //wv.loadData(data, mimeType, encoding); // wv.loadUrl("http://f.hiphotos.baidu.com/image/h%3D200/sign=650d5402a318972bbc3a07cad6cd7b9d/9f2f070828381f305c3fe5bfa1014c086e06f086.jpg"); } public class A { @JavascriptInterface public void show(String s) { Toast.makeText(MainActivity.this, s, 0).show(); } } }
<!-- /assets/a.html --> <!doctype html> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> <script type="text/javascript"> function aa() { var w=document.getElementById("hhh"); w.style.backgroundColor="#ff0000"; } function show() { w=document.getElementById("input"); bridge.show(w.value); } </script> </head> <body> <div style="background-color:#335577; width:30px; height:50px" id="hhh"> </div> <input type="text" id="input" /> <button onClick="aa();">哈哈</button><br/> <button onClick="show();">哈哈</button> </body> </html>
<!-- /res/layout/activity_main.xml --> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="${relativePackage}.${activityClass}" > <WebView android:id="@+id/wv" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>