Mono Droid中找不到onClick事件

5

I have the following layout:

<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中的代码:

[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个回答

8

如果你在Java中编写代码,它会按照你的期望运行。在MonoDroid中,这个功能未被实现。 - jpobst
1
我明白了,谢谢。是否有关于MonoDroid不支持的文档? - Chris Hawkins
2
给这个回答点赞。真希望在浪费时间之前能在其他地方看到这些信息。 - TonyG
1
作为最新消息,MonoDroid现在支持此功能:http://docs.xamarin.com/android/advanced_topics/Java_Integration?highlight=export#ExportAttribute_and_ExportFieldAttribute - jpobst
1
算了,我想通了:只需在 onClick 方法上方加上 [Export] 属性,并确保在项目中添加对 Mono.Android.Export 的引用即可。 - paz
显示剩余2条评论

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接