c# - 在 Xamarin 中从 JavaScript 调用 C#

标签 c# android xamarin

正在尝试测试 this example ,但发现它对我不起作用,我使用 API19,我的代码是:

using System;
using Android.App;
using Android.Content;  
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Webkit;
using Java.Interop;

namespace App3
{
[Activity(Label = "App3", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
    int count = 1;

    const string html = @"
         <html>
         <body>
             <p>Demo calling C# from JavaScript</p>
             <button type=""button"" onClick=""CSharp.ShowToast()"">Call C#   </button>
        </body>
    </html>";

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        // Get our button from the layout resource,
        // and attach an event to it
        Button button = FindViewById<Button>(Resource.Id.MyButton);

        WebView localWebView = FindViewById<WebView>(Resource.Id.LocalWebView);
        localWebView.SetWebViewClient(new WebViewClient()); // stops request going to Web Browser
        localWebView.Settings.JavaScriptEnabled = true;
        // localWebView.LoadUrl("http://developer.xamarin.com");
        // localWebView.LoadUrl("file:///android_asset/index.html");
        localWebView.LoadData(html, "text/html", null);

        button.Click += delegate { button.Text = string.Format("{0} clicks!", count++); };
    }
}
    class MyJSInterface : Java.Lang.Object
    {
        Context context;

        public MyJSInterface(Context context)
        {
            this.context = context;
        }

        [Export]
        [JavascriptInterface]
        public void ShowToast()
        {
            Toast.MakeText(context, "Hello from C#", ToastLength.Short).Show();
        }
    }
}

我这里有什么错误!

注意:我已经添加了对 Mono.Android.Export 的引用(因此您可以使用 [Export] 注释):

最佳答案

在加载 HTML 之前,您需要将 MyJavascriptInterface 的实例添加到 localWebView:

WebView localWebView = FindViewById<WebView>(Resource.Id.LocalWebView);
localWebView.SetWebViewClient(new WebViewClient()); // stops request going to Web Browser
localWebView.Settings.JavaScriptEnabled = true;

// Add an instance of the Javascript interface named "CSharp"
localWebView.AddJavascriptInterface(new MyJSInterface(this), "CSharp");

localWebView.LoadData(html, "text/html", null);

关于c# - 在 Xamarin 中从 JavaScript 调用 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39631796/

相关文章:

c# - xslt 转换的正确语法

c# - 我如何在 .Net 中操作 token 权限?

c# - 从另一个类访问表单控件

Java静态类变量初始化效率

c# Xamarin UITextField 设置光标位置

c# - 如何在 Xamarin 表单 NavigationPage 中更改背景色

C# 到 C++ 数组?

android - 使用 android api 23 及更多时,我没有发现蓝牙 gatt 服务

android-如何检测我的应用程序错误并修复它们

c# - 如何在 xamarin 中获取 ip 网络连接版本(是 IPv4 还是 IPv6)?