标签:android blog io os java sp strong div on
为了方便网页和应用的交互,安卓系统WebView提供JavaScript网页脚本调用Java类方法的机制。只要调用addJavascriptInterface方法即可映射一个Java对象到JavaScript对象上。
MainActivity.java代码:
package com.apple.browser; import android.annotation.SuppressLint; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.Toast; public class MainActivity extends Activity { private WebView webView; private Activity activity; @SuppressLint("SetJavaScriptEnabled") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); activity = this; webView = (WebView) findViewById(R.id.webview); webView.loadUrl("file:///android_asset/index.html"); final WebSettings settings = webView.getSettings(); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setJavaScriptEnabled(true); settings.setSupportZoom(true); webView.addJavascriptInterface(new JSInvokeClass(), "js2java"); } public final class JSInvokeClass { public void back() { // activity.finish(); Toast.makeText(activity, "通过js调用的Java方法", Toast.LENGTH_SHORT).show(); } } }
HTML中代码:
<input type=button name=smt value=‘invoke java‘ onclick="javascript:window.js2java.back();">
XML布局代码:
略
标签:android blog io os java sp strong div on
原文地址:http://www.cnblogs.com/magics/p/4089593.html