11

What I'm doing is this

Button button1 = FindViewById<Button>(Resource.Id.button1);

button1.SetOnClickListener(new View.OnClickListener()
    {
        public void onClick(View v)
        {
            // Perform action on click
        }
    });

but for some reasons I'm getting OnClickListener underlined with red. and I can't do anything to launch a function when I click my button .

0

3 Answers 3

20

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

Sign up to request clarification or add additional context in comments.

Comments

4

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" :)

Comments

4

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..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.