2012-02-22 2 views
2

저는 webview를 사용하여 자바 스크립트에서 모노 도이드 메서드 (C#)를 호출하는 방법의 예제를 찾고 있습니다. 같은자바 스크립트 예제에서 monodroid 메서드를 호출하십시오.

뭔가 :

자바 스크립트 :

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

} 
관련 문제