views:

894

answers:

4

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.

+1  A: 

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

Eclipsed4utoo
Note that this is new to Android 1.6, IIRC.
CommonsWare
+1  A: 

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
+4  A: 

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
I didn't realize that Java didn't have a delegate type - thanks for clearing that up!
James Cadd
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
A: 

I am having a problem right now with setOnClickListener.

When i put this following line:

button.setOnClickListener(this);

And run the application then it does not run and show a message that "Application closed forcefully".

Could you please help me how I can set button onclick event in Android 2.2

Thanks Chandu

chandu