很簡單的直接上代碼javascript
<uses-permission android:name="android.permission.INTERNET" />
assets/web.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=gb2312">
<script type="text/javascript">
function javacalljs(){ document.getElementById("content").innerHTML = "<br\>JAVA調用了JS的函數"; } function javacalljswith(arg){ document.getElementById("content").innerHTML = ("<br\>"+arg); } </script>
</head>
<body> HTML 內容顯示 <br/>
<h1>
<div id="content">內容顯示</div>
</h1>
<br/>
<input type="button" value="點擊調用java代碼" onclick="window.android.startFunction()"/>
<br/>
<input type="button" value="點擊調用java代碼並傳遞參數" onclick="window.android.startFunction('http://blog.csdn.net/Leejizhou')"/>
</body>
</html>
package com.leejz.jsdemo; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.webkit.JavascriptInterface; import android.webkit.WebView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private WebView contentWebView = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); contentWebView = (WebView) findViewById(R.id.webview); // 啓用javascript contentWebView.getSettings().setJavaScriptEnabled(true); // 從assets目錄下面的加載html contentWebView.loadUrl("file:///android_asset/web.html"); contentWebView.addJavascriptInterface(MainActivity.this, "android"); //無參調用Js點擊
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 無參數調用 WebView中顯示 JAVA調用了JS的函數 contentWebView.loadUrl("javascript:javacalljs()"); } }); //有參調用Js點擊
findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 傳遞參數調用 WebView中顯示 www.baidu.com contentWebView.loadUrl("javascript:javacalljswith(" + "'www.baidu.com'" + ")"); } }); } //因爲安全緣由 須要加 @JavascriptInterface @JavascriptInterface public void startFunction() { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, "吐司", Toast.LENGTH_SHORT).show(); } }); } @JavascriptInterface public void startFunction(final String text) { runOnUiThread(new Runnable() { @Override public void run() { new AlertDialog.Builder(MainActivity.this).setMessage(text).show(); } }); } }