【问题标题】:call monodroid method from javascript example从 javascript 示例调用 monodroid 方法
【发布时间】:2013-01-24 07:20:55
【问题描述】:

我正在寻找如何使用 webview 从 javascript 调用 monodroid 方法 (C#) 的示例。

类似:

javascript:

<a href="#" onclick="window.android.callAndroid('Hello from Browser')"> 
   Call Android from JavaScript</a>

C#

public class LocalBrowser extends Activity {
...
   private class MyClass {
      public void callAndroid(final String arg) { 
               textView.setText(arg);
      }
   }
  }

谢谢

【问题讨论】:

    标签: mono xamarin.android


    【解决方案1】:

    这是我用来最终为我解决此问题的示例。迟到总比不到好。

    密切注意函数的修饰,并确保在您的引用中包含 Mono.Android.Export。

    https://github.com/xamarin/monodroid-samples/blob/master/WebViewJavaScriptInterface/WebViewJavaScriptInterface/JavaScriptInterfaceActivity.cs

    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 WebViewJavaScriptInterface
    {
    [Activity (Label = "Mono WebView ScriptInterface", MainLauncher = true)]
    public class JavaScriptInterfaceActivity : Activity
    {
        const string html = @"
    <html>
    <body>
    <p>This is a paragraph.</p>
    <button type=""button"" onClick=""Foo.bar('test message')"">Click Me!</button>
    </body>
    </html>";
    
        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);
    
            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);
    
            WebView view = FindViewById<WebView> (Resource.Id.web);
            view.Settings.JavaScriptEnabled = true;
            view.SetWebChromeClient (new WebChromeClient ());
            view.AddJavascriptInterface (new Foo (this), "Foo");
            view.LoadData (html, "text/html", null);
        }
    }
    
    class Foo : Java.Lang.Object
    {
        public Foo (Context context)
        {
            this.context = context;
        }
    
        public Foo (IntPtr handle, JniHandleOwnership transfer)
            : base (handle, transfer)
        {
        }
    
        Context context;
    
        [Export ("bar")]
        // to become consistent with Java/JS interop convention, the argument cannot be System.String.
        public void Bar (Java.Lang.String message)
        {
            Console.WriteLine ("Foo.Bar invoked!");
            Toast.MakeText (context, "This is a Toast from C#! " + message, ToastLength.Short).Show ();
        }
    }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-27
      • 2016-08-30
      • 2013-09-16
      • 2020-03-23
      • 1970-01-01
      相关资源
      最近更新 更多