Xamarin XML android:onClick回调方法

Jon*_*hih 4 android xamarin.android xamarin

这是我的XML代码:

    <Button
    android:text="Button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/MyButton"
    android:id="@+id/button1"
    android:onClick="sayHellow" /> //RELEVANT PART
Run Code Online (Sandbox Code Playgroud)

这是我的主要活动:

[Activity(Label = "FFFF", MainLauncher = true, Icon = "@drawable/icon", Theme = "@style/Theme.AppCompat.Light")]
public class MainActivity : AppCompatActivity
{
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);
    }
    public void sayHellow(View v) //CALLBACK FUNCTION
    {
        Snackbar.Make(v, "My text", Snackbar.LengthLong)
            .Show();
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是我遇到运行时错误,调试窗口抱怨Button找不到“ sayHellow”函数,但是如您所见,我根据文档声明了所有内容。

jze*_*ino 6

您必须导出方法:

[Export("sayHellow")]
public void sayHellow(View v)
{
    Snackbar.Make(v, "My text", Snackbar.LengthLong).Show();
}
Run Code Online (Sandbox Code Playgroud)

并且您必须将引用添加到 Java.Interop.dll

在此处输入图片说明


一个更简单的解决方案是:

Button button = FindViewById<Button> (Resource.Id.myButton);

button.Click += delegate {
    //Clicked
};
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢,在我引用了Mono.Android.Export.dll之后,我不得不使用Java.Interop.Export,但是您说得对,它正在运行。今天你很帮我,我很感激。 (2认同)