Xamarin xml android:onClick callback method

三世轮回 提交于 2020-01-02 06:33:51

问题


This is my XML code:

    <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

And this is my main activity:

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

Problem is I get a runtime error and the debug window complains that Buttoncould not find "sayHellow" function, but as you can see I declared everything according to the docs.


回答1:


You must export the method:

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

And you must add the reference to the Java.Interop.dll


A simpler solution would be:

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

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


来源:https://stackoverflow.com/questions/37800931/xamarin-xml-androidonclick-callback-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!