在androidwebview中使用javascript
我正在尝试从webview中的javascript界面启动一个活动。 这个例子展示了一个祝酒词。我怎么能叫一个班级而不是祝酒呢在androidwebview中使用javascript,javascript,android,webview,Javascript,Android,Webview,我正在尝试从webview中的javascript界面启动一个活动。 这个例子展示了一个祝酒词。我怎么能叫一个班级而不是祝酒呢 public class JavaScriptInterface { Context mContext; /** Instantiate the interface and set the context */ JavaScriptInterface(Context c) { mContext = c; } /** Show a toast from the
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);
}
函数showAndroidToast(toast){
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>
函数displaymessage()
{
JSInterface.changeActivity();
}
希望这对您有所帮助……如果您在android 4.2或更高版本上运行,您还需要在android代码中的
changeActivity
方法的顶部添加@android.webkit.JavascriptInterface注释。
更多信息,请参见此内容。我没有足够的经验回答,但您是否阅读过此内容:好的,我只是没有看到您在webview中启用javascript的任何地方,尽管这是相关的。您没有明白我的问题,我想呼吁您的意图,而不是敬酒。我已经让祝酒的例子起作用了。无论如何,我想在没有任何网络视图的情况下完成它。这只是内部的可能。谢谢你,我的朋友。它几乎帮助我解决了我的问题。@Common我应该把上面的html代码放在单独的html文件中?这对从javascript调用android函数很有用,但是有任何方法可以从android代码调用javascript函数吗?这个html文件的位置是什么?我有一个问题,html页面放在哪里?