2016-09-22 98 views
1

試圖測試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(這樣你就可以使用[出口]註釋)參考:

回答

1

您需要加載HTML之前添加MyJavascriptInterfacelocalWebView的實例:

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); 
+0

就加入它,但仍然沒有顯示任何東西:( –

+0

你有確切的代碼我已經編輯我的回答?這工作逐字我。 – matthewrdev

+1

感謝@mattherwrdev,看起來我有2失誤,第一個是你修復的那個,另一個是在WevView接口上面添加原生按鈕,它是廁所ks他們原生和webView不能一起工作。 –