从JavaScript调用Android方法

我搜查了,但我没有find答案。 我正在开发基于webview的Android应用程序,使用HTML5和JavaScript。 我可以调用Android方法,比如JavaScript中的makeToast()吗?

Solutions Collecting From Web of "从JavaScript调用Android方法"

您可以通过将JavaScript接口添加到WebView并将特定的方法暴露给Web视图中运行的JavaScript代码来实现此目的。 换句话说,你需要在你的activity / fragment中创build的一个方法中调用Android的Toast类。

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"> <WebView android:id="@+id/web_view" android:layout_width="fill_parent" android:layout_height="fill_parent"/> </RelativeLayout> 

MainActivity.java

 public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); WebView webView = (WebView)findViewById(R.id.web_view); webView.loadUrl("file:///android_asset/web.html"); webView.getSettings().setJavaScriptEnabled(true); webView.addJavascriptInterface(new WebViewJavaScriptInterface(this), "app"); } /* * JavaScript Interface. Web code can access methods in here * (as long as they have the @JavascriptInterface annotation) */ public class WebViewJavaScriptInterface{ private Context context; /* * Need a reference to the context in order to sent a post message */ public WebViewJavaScriptInterface(Context context){ this.context = context; } /* * This method can be called from Android. @JavascriptInterface * required after SDK version 17. */ @JavascriptInterface public void makeToast(String message, boolean lengthLong){ Toast.makeText(context, message, (lengthLong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT)).show(); } } } 

资产/ web.html

 <!DOCTYPE html> <html> <head> <title>JavaScript View</title> <script type="text/javascript"> function showToast(){ var message = document.getElementById("message").value; var lengthLong = document.getElementById("length").checked; /* Call the 'makeToast' method in the Java code. 'app' is specified in MainActivity.java when adding the JavaScript interface. */ app.makeToast(message, lengthLong); return false; } /* Call the 'showToast' method when the form gets submitted (by pressing button or return key on keyboard). */ window.onload = function(){ var form = document.getElementById("form"); form.onsubmit = showToast; } </script> </head> <body> <form id="form"> Message: <input id="message" name="message" type="text"/><br /> Long: <input id="length" name="length" type="checkbox" /><br /> <input type="submit" value="Make Toast" /> </form> </body> </html> 

吐司消息

只是因为它更方便(布局):

 <?xml version="1.0" encoding="utf-8"?> <WebView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/webView" android:layout_width="fill_parent" android:layout_height="fill_parent" />