Android - How to set a named method in button.setOnClickListener() Android - How to set a named method in button.setOnClickListener() android android

Android - How to set a named method in button.setOnClickListener()


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.


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