找不到Mono Droid onClick事件

时间:2011-07-17 21:05:55

标签: c# android mono xamarin.android

我有以下布局:

<Button android:id="@+id/MyButton"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/Hello"
    android:clickable="true"
    android:onClick="Foo"
/>

这在我的活动中:

[Activity(Label = "LayoutTest", MainLauncher = true, Icon = "@drawable/icon")]
public class Activity1 : Activity
{
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        SetContentView(Resource.Layout.Main);
    }

    public void Foo(View v)
    {
        Toast.MakeText(v.Context, "Bar", ToastLength.Long).Show();
    }
}

当我在模拟器中调试此应用程序时,当我点击MyButton时,应用程序崩溃,并在日志中显示以下内容:

E/AndroidRuntime(  507): FATAL EXCEPTION: main
E/AndroidRuntime(  507): java.lang.IllegalStateException: Could not find a method    Foo(View) in the activity class helloworld.Activity1 for onClick handler on view class android.widget.Button with id 'MyButton'
E/AndroidRuntime(  507):    at android.view.View$1.onClick(View.java:2059)
E/AndroidRuntime(  507):    at android.view.View.performClick(View.java:2408)
E/AndroidRuntime(  507):    at android.view.View$PerformClick.run(View.java:8816)
E/AndroidRuntime(  507):    at android.os.Handler.handleCallback(Handler.java:587)
E/AndroidRuntime(  507):    at android.os.Handler.dispatchMessage(Handler.java:92)

2 个答案:

答案 0 :(得分:8)

MonoDroid不支持以这种方式注册事件。

您需要自己在活动的OnCreate中连接事件。

<强>更新 作为更新,MonoDroid现在支持:http://docs.xamarin.com/guides/android/advanced_topics/java_integration_overview/working_with_jni/#_ExportAttribute_and_ExportFieldAttribute

答案 1 :(得分:5)

除了[Export ("javamethodname")]方法的onClick属性和对Mono.Android.Export的引用外,您还需要

using Java.Interop;