我正在研究一个关于在Android上嵌入web应用程序的项目,遵循WebView演示,但是当Android应用程序调用javascript函数'wave'时我需要调用gwt函数:
<html>
<script language="javascript">
/* This function is invoked by the activity */
function wave(s) {
// call a gwt function and
// pass 's' to the gwt function
}
</script>
<body>
<!-- Calls into the javascript interface for the activity -->
<a onClick="window.demo.clickOnAndroid()"><div style="width:80px;
...
</div></a>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
关于如何实现这一点的任何想法?
您需要将要从javascript调用的任何方法导出到javascript全局范围.这意味着你不能从手写的javascript中调用任意java方法.您必须提前计划并在javascript范围中公开必要的方法.
这个过程非常简单:
GWT JSNI文档中的一个示例以及其他注释:
package mypackage;
public MyUtilityClass
{
//Method to be called from javascript, could be in any other class too
public static int computeLoanInterest(int amt, float interestRate,
int term) { ... }
//This method should be called during application startup
public static native void exportStaticMethod() /*-{
//the function named here will become available in javascript scope
$wnd.computeLoanInterest =
$entry(@mypackage.MyUtilityClass::computeLoanInterest(IFI));
}-*/;
}
Run Code Online (Sandbox Code Playgroud)
编辑:
将参数传递给Java方法:
当您从javascript调用带有参数的Java方法时,您需要使用特定的语法:
[instance-expr.]@class-name::method-name(param-signature)(arguments)
Run Code Online (Sandbox Code Playgroud)
例如,调用带有String参数的静态方法将如下所示:
@com.google.gwt.examples.JSNIExample::staticFoo(Ljava/lang/String;)(s);
Run Code Online (Sandbox Code Playgroud)
请注意,当我们调用静态方法时,'instance-expr.' 省略.其余代码是完全限定的类名,后跟::和方法名.该Ljava/lang/String;方法名称后,指定我们需要调用,需要一个String对象作为参数的方法.最后s是该参数的实际值.
请记住,Ljava/lang/String;在我们的示例中,param-signature 在语法中使用JNI类型签名规范,并且即使存在多个具有相同名称的重载方法,GWT编译器也需要选择正确的方法.param-signature即使方法没有超载,也需要A.