按钮处理程序在axml布局中声明

时间:2015-11-25 18:19:53

标签: xamarin.android

我猜这很容易,但似乎无法确定。

我想在axml文件中定义一个按钮,并将点击链接到处理程序。我知道我可以使用FindViewById<Button>(Resource.Id.Button2).Click += buttonClick;手动设置处理程序,但是我想知道是否有必要。

如何在axml文件中使用android:onClick="buttonClick"的优点绑定处理程序?引发的错误是

Could not find a method buttonClick(View) in the activity class md....Activity1 for onClick handler on view class android.widget.Button with id 'Button1'

[Activity (Label = "SlidingMenuExample", MainLauncher = true)]
public class Activity1 : Activity
{
    protected override void OnCreate(Bundle bundle) {
        base.OnCreate(bundle);
        SetContentView (Resource.Layout.menu);  
    }

    public void buttonClick(object sender, EventArgs e) {
    }

    // This seems similar to the Java approaches. Why doesn't it work?
    //public void buttonClick(View view) {
    //} 

}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button
        android:id="@+id/Button2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="button 2"
        android:onClick="buttonClick" />
</LinearLayout>

感谢。

1 个答案:

答案 0 :(得分:1)

当然可以这样做。您需要添加对Mono.Android.Export的引用。

然后你需要注释你的方法,如:

[Export("buttonClick")]
private void ButtonClick(View view)
{

}

如果您没有注释该方法,Java世界将不会知道您在Activity中的方法。