2016-06-13 109 views
1

这是我的XML代码:Xamarin XML安卓的onClick回调方法

<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找不到“sayHellow”函数,但正如您所看到的,我根据文档声明了一切。

回答

2

您必须导出方法:

[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 
}; 
+1

非常感谢,我在引用'Mono.Android.Export.dll'后不得不使用'Java.Interop.Export',但你是对的,它正在工作。 今天你帮了我很多,我很感激。 –

+0

是的,我已经在我的回答中说过,并为它添加了截图。 – jzeferino