调用C#从JavaScript在Xamarin
问题描述:
试图测试this example,却发现它不在我的工作,我用API19,我的代码是:调用C#从JavaScript在Xamarin
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(这样你就可以使用[出口]注释)参考:
答
您需要加载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);
就加入它,但仍然没有显示任何东西:( –
你有确切的代码我已经编辑我的回答?这工作逐字我。 – matthewrdev
感谢@mattherwrdev,看起来我有2失误,第一个是你修复的那个,另一个是在WevView接口上面添加原生按钮,它是厕所ks他们原生和webView不能一起工作。 –