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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With