从javascript示例中调用monodroid方法 [英] call monodroid method from javascript example

查看:42
本文介绍了从javascript示例中调用monodroid方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am looking for an example of how to call a monodroid method (C#) from javascript, using a webview.

类似的东西:

javascript:

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);
      }
   }
  }

谢谢

推荐答案

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

This is the example I used to finally solve this for me. Better late than never.

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

Pay close attention to the decoration of the function and be sure to include Mono.Android.Export in your references.

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 ();
    }
}

}

这篇关于从javascript示例中调用monodroid方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆