我正在从我的 WebView
调用一个方法。每当单击 WebView
中的按钮时,该方法都会执行 Toast
。它工作正常,但当我传递参数时它不起作用。当我传递参数时,该方法没有被执行。
这是我在 strings.xml
中的 javascript
-
<string name="details">
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width; user-scalable=0;" />
<title>My HTML</title>
</head>
<body>
<h1>MyHTML</h1>
<p id="mytext">Hello!</p>
<input type="button" value="Say hello" onClick="showAndroidToast('Hello world!')" />
<script language="javascript">
function showAndroidToast(toast) {
AndroidFunction.showToast(toast);
}
function callFromActivity(msg){
document.getElementById("mytext").innerHTML = msg;
}
</script>
</body>
</html></string>
这是我的 Activity
代码-
String str = "<html><body>"
+ getString(R.string.details)
+ "</body></html>";
webview.addJavascriptInterface(new MyJavaScriptInterface(this),
"AndroidFunction");
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webview.loadDataWithBaseURL(null, str, "text/html", "utf-8", null);
这是我的 MyJavaScriptInterface
类:
public class MyJavaScriptInterface {
Context mContext;
MyJavaScriptInterface(Context c) {
Log.d("tag", "cls");
mContext = c;
}
public void showToast(String toast) {//without the argument this method executes
Log.d("tag", "msg");
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
最佳答案
您的 JavaScript 语法不正确:
function showAndroidToast(String toast) {
AndroidFunction.showToast(String toast);
}
需要:
function showAndroidToast(toast) {
AndroidFunction.showToast(toast);
}
其他提示:
您通过包装
getString()
来复制 HTML 标记。与<html><body>
。这已经包含在您的strings.xml
中:webview.loadDataWithBaseURL(null, getString(R.string.details), "text/html", "utf-8", null);
您不应该将所有 HTML 存储在
strings.xml
中。将其作为 HTML 文件存储在 Assets 文件夹中并调用:webview.loadUrl("file:///android_asset/details.html");
你不应该使用这样的侵入性Javascript,这将是以后维护的一场噩梦。阅读this article了解更好的普通 Javascript 开发方法。
关于java - 使用 Javascript 从 WebView 调用 Activity 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19858028/