C# Xamarin OnClick function

前端 未结 3 422

What I\'m doing is this

Button button1 = FindViewById
相关标签:
3条回答
  • 2021-01-02 08:28

    The Xamarin.Android way of doing a SetOnClickListener is via C# style events:

    Button button1 = FindViewById<Button>(Resource.Id.button1);
    button1.Click += (sender, e) => {
       // Perform action on click
    };
    

    Required reading for Xamarin's Android Events and Listeners

    0 讨论(0)
  • 2021-01-02 08:31

    The real issue here is in your SetOnClickListener you are setting an inline anonymous class implementing OnClickListener interface.

    This is not supported in C#, From the C# programming guide, you can find,

    Anonymous types are class types that consist of one or more public read-only properties. No other kinds of class members such as methods or events are allowed. An anonymous type cannot be cast to any interface or type except for object.

    But it doesn't mean that you cannot use SetOnClickListener at all.

    You can either do button1.SetOnClickListener(this) and implement your OnClickListener in the same class

    or

    create a class (can be inner class) implements OnClickListener with your implementation and pass an it's instance to your SetOnClickListener

    In both ways, your are obeying C#'s "Real Name Policy" :)

    0 讨论(0)
  • 2021-01-02 08:37

    No need of using either delegates or c# style events, you can use both depending on the class being used. Remember that the View.IOnclicklistener is an interface so inherit from it like so,

    public class myactivity : AppcompatActivity, View.IonClickListener
    

    It prompts you to implement the onclick method of the interface like below,,

    public void OnClick(View v)
            {
                throw new NotImplementedException();
            }
    

    You can use a mixture of c# style events and event listeners. What java can do Xamarin can do ..This is the correct answer to this question i believe..

    0 讨论(0)
提交回复
热议问题