12

Most samples that I see appear to use an anonymous method in a call like button.setOnClickListener(). Instead, I'd like to pass in a method defined on the Activity class that I'm working in. What's the Java/Android equivalent of the following event handler wiring in C#?

Button myButton = new Button();
myButton.Click += this.OnMyButtonClick;

Where:

private void OnMyButtonClick(object sender, EventArgs ea)
{
}

Essentially, I'd like to reuse a non-anonymous method to handle the click event of multiple buttons.

James Cadd
  • 12,136
  • 30
  • 85
  • 134

3 Answers3

16

Roman Nurik's answer is almost correct. View.OnClickListener() is actually an interface. So if your Activity implements OnClickListener, you can set it as the button click handler.

public class Main extends Activity implements OnClickListener {

      public void onCreate() {
           button.setOnClickListener(this);
           button2.setOnClickListener(this);
      }

      public void onClick(View v) {
           //Handle based on which view was clicked.
      }
}

There aren't delegates as in .Net, so you're stuck using the function based on the interface. In .Net you can specify a different function through the use of delegates.

GrkEngineer
  • 2,122
  • 19
  • 20
  • I didn't realize that Java didn't have a delegate type - thanks for clearing that up! – James Cadd Dec 29 '09 at 15:29
  • 1
    I actually just came across this article (it's actually an old article). Somewhat interesting comments about their decission not to use delegates. I don't know if I agree because I loved using delegates in .Net. http://java.sun.com/docs/white/delegates.html – GrkEngineer Dec 29 '09 at 17:02
9

The argument to View.setOnClickListener must be an instance of the class View.OnClickListener (an inner class of the View class).. For your use case, you can keep an instance of this inner class in a variable and then pass that in, like so:

View.OnClickListener clickListener = new OnClickListener() {
    public void onClick(View v) {
        // do something here
    }
};

myButton.setOnClickListener(clickListener);
myButton2.setOnClickListener(clickListener);

If you need this listener across multiple subroutines/methods, you can store it as a member variable in your activity class.

Roman Nurik
  • 29,665
  • 7
  • 84
  • 82
1

The signature of the method will need to be this...

public void onMyButtonClick(View view){

}

If you are not using dynamic buttons, you can set the "onClick" event from the designer to "onMyButtonClick". That's how I do it for static buttons on a screen. It was easier for me to relate it to C#.

Ryan Alford
  • 7,514
  • 6
  • 42
  • 56