我正在尝试从Webview中的javascript界面开始一项活动。该示例显示了一个烤面包。我怎么能称呼课程而不是敬酒?
public class JavaScriptInterface { Context mContext; /** Instantiate the interface and set the context */ JavaScriptInterface(Context c) { mContext = c; } /** Show a toast from the web page */ public void showToast(String toast) { Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show(); } }
这是html页面。
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" /> <script type="text/javascript"> function showAndroidToast(toast) { Android.showToast(toast); }
您必须先在Webview上注册JavaScriptInterface。JavaScriptInterFace可以是一个内部类,如下所示。此类将具有您可以从html页面(通过javaScript)调用的函数,并且可以在该函数内部编写代码以更改活动。
这是适合您的解决方案:
public class JavascriptInterfaceActivity extends Activity { /** Called when the activity is first created. */ WebView wv; JavaScriptInterface JSInterface; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); wv = (WebView)findViewById(R.id.webView1); wv.getSettings().setJavaScriptEnabled(true); // register class containing methods to be exposed to JavaScript JSInterface = new JavaScriptInterface(this); wv.addJavascriptInterface(JSInterface, "JSInterface"); wv.loadUrl("file:///android_asset/myPage.html"); } public class JavaScriptInterface { Context mContext; /** Instantiate the interface and set the context */ JavaScriptInterface(Context c) { mContext = c; } @android.webkit.JavascriptInterface public void changeActivity() { Intent i = new Intent(JavascriptInterfaceActivity.this, nextActivity.class); startActivity(i); finish(); } } }
这是HTML页面
<html> <head> <script type="text/javascript"> function displaymessage() { JSInterface.changeActivity(); } </script> </head> <body> <form> <input type="button" value="Click me!" onclick="displaymessage()" /> </form> </body> </html>
希望这可以帮助…