[英]Calling C# from JavaScript in Xamarin
試圖測試 這個例子,但發現它對我不起作用,我使用 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.