我在 Visual Studio 的输出中收到错误:
Uncaught TypeError: Foo.run is not a function
当尝试运行 Index.html 中的 JavaScript 函数来调用 C# 方法时:
<button type="button" onClick="Foo.run()">Click Me!</button>
我尝试添加符号:
[JavascriptInterface]
[Export("Run")]
我使用 CrossWalk WebView 不起作用,所以我添加了:
[Org.Xwalk.Core.JavascriptInterface]
[Export("Run")]
这是我的完整 C# 代码:
using Android.App;
using Android.Widget;
using Android.OS;
using System;
using Android.Views;
using Android.Webkit;
using Java.Interop;
using Android.Content;
namespace XWalk
{
[Activity(Label = "XWalk", MainLauncher = true)]
public class MainActivity : Org.Xwalk.Core.XWalkActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
}
protected override void OnXWalkReady()
{
var view = new RelativeLayout(this.BaseContext);
var mp = ViewGroup.LayoutParams.MatchParent;
var xwv = new Org.Xwalk.Core.XWalkView(this.BaseContext, this);
view.AddView(xwv);
this.AddContentView(view, new ViewGroup.LayoutParams(mp, mp));
xwv.AddJavascriptInterface(new Foo(this), "Foo");
xwv.LoadUrl("file:///android_asset/index.html");
}
class Foo : Java.Lang.Object, Java.Lang.IRunnable
{
Context context;
public Foo(Context context)
{
this.context = context;
}
[Org.Xwalk.Core.JavascriptInterface]
//[Export]
///[JavascriptInterface]
[Export("Run")]
public void Run()
{
Toast.MakeText(context, "This is a Toast from C#!", ToastLength.Short).Show();
}
}
}
}
我的目标是 Android 4.1 及更高版本,所以我使用了
Java.Lang.IRunnable
正如 Xamarin 文档中提到的 但是单击 HTML 按钮时的输出结果:
Uncaught TypeError: Foo.run is not a function
更新
对于任何想要在这里构建它的人来说,它是如何与我合作的:
下载项目: https://github.com/KevinGliewe/Xamarin.Android.XWalk
现在该项目不使用共享人行横道库,但我希望它共享库,所以我所做的是在提取整个项目后在项目中编辑此文件“XWalk.Binding.csproj” 并更改:
<ItemGroup>
<LibraryProjectZip Include="Jars\xwalk_core_library-23.53.589.4-x86.aar" />
</ItemGroup>
至:
<ItemGroup>
<LibraryProjectZip Include="Jars\xwalk_shared_library-23.53.589.4.aar" />
</ItemGroup>
并从以下位置下载共享库: https://download.01.org/crosswalk/releases/crosswalk/android/maven2/org/xwalk/
并将其放入 XWalk.Binding 项目内的 Jars 文件夹中
之后打开解决方案项目,只需构建整个项目并运行它.. 如果您想要发布版本,请确保 XWalk.Binding 项目属性中的选项 在“构建”选项卡中,选中“定义调试常量”和“定义跟踪常量”,否则在使用 C# 代码时将不会检测到人行横道库
构建并运行它,它就会工作......
最佳答案
<button type="button" onClick="Foo.run()">Click Me!</button>
更改为:
<button type="button" onClick="Foo.Run()">Click Me!</button>
我尝试这样调用它,并且成功了
关于javascript - 在 Android Xamarin CrossWalk Webview 中从 Javascript 调用 C# 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54053326/