Xamarin xml android:onClick回调方法

时间:2016-06-13 23:57:50

标签: android xamarin xamarin.android

这是我的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

这是我的主要活动:

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

问题是我收到运行时错误,调试窗口抱怨Button无法找到&#34; sayHellow&#34;功能,但正如你所看到的,我根据文档声明了一切。

1 个答案:

答案 0 :(得分:4)

您必须导出方法:

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

您必须添加对Java.Interop.dll

的引用

enter image description here

更简单的解决方案是:

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

button.Click += delegate {
    //Clicked
};