![](/img/trans.png)
[英]get position of a webview on the screen using javascript in android
[英]using javascript in 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 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>
希望这可以帮助...
如果您在Android 4.2或更高版本上运行,还需要在Android代码中的changeActivity
方法之上添加@ android.webkit.JavascriptInterface注释。 请参阅此链接了解更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.