2012-02-22 15 views
2

私は、webviewを使用して、javascriptからモノドロイドメソッド(C#)を呼び出す方法の例を探しています。JavaScriptからmonodroidメソッドを呼び出す例

のような何か:

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

おかげ

答えて

2

は、これは私が最終的に私のためにこれを解決するために使用した例です。遅くなく良い。

関数の装飾に細心の注意を払い、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(); 
    } 
} 

} 
関連する問題